本文整理汇总了C#中Repository.GetById方法的典型用法代码示例。如果您正苦于以下问题:C# Repository.GetById方法的具体用法?C# Repository.GetById怎么用?C# Repository.GetById使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Repository
的用法示例。
在下文中一共展示了Repository.GetById方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main()
{
//Create all the repos I need
var repo = new Repository();
//Get some entities
var person = repo.GetById<Person>(1);
var company = repo.GetById<Company>(2);
var order = repo.GetById<Order>(3);
//Chagne and save entities
person.FirstName = "Bob";
company.CompanyName = "Bob's House of Propane and Day Old Sushi";
order.OrderTotal = 1000000;
var personId = repo.Save(person);
var companyId = repo.Save(company);
var orderId = repo.Save(order);
Console.WriteLine("Saved person, Id is {0}", personId);
Console.WriteLine("Saved company, Id is {0}", companyId);
Console.WriteLine("Saved order, Id is {0}", orderId);
Console.ReadKey();
}
示例2: TestChangeCity
public void TestChangeCity()
{
Guid id = Guid.NewGuid();
Guid companyId = Guid.NewGuid();
Guid countryId = Guid.NewGuid();
Guid cityId = Guid.NewGuid();
Repository<Address> repository = new Repository<Address>(ObjectFactory.Create<IEventStore>());
Address address = repository.GetById(id);
address.Create(id, Owner.Company, companyId);
address.ChangeCountry(countryId);
address.ChangeCity(cityId);
Assert.AreEqual(Owner.Company, address.State.Owner);
Assert.AreEqual(countryId, address.State.CountryId);
Assert.AreEqual(cityId, address.State.CityId);
Assert.AreEqual(3, address.GetUncommittedChanges().Count);
address.Commit();
Assert.AreEqual(0, address.GetUncommittedChanges().Count);
address.LoadFromHistory(new List<Event> {new AddressEvents.NoteChanged(id, "this note should be applied to aggregate")});
Assert.AreEqual("this note should be applied to aggregate", address.State.Note);
}
示例3: NothingShouldGoBang
public void NothingShouldGoBang()
{
var factStore = new MemoryFactStore();
var aggregateRebuilder = new AggregateRebuilder(factStore);
var snapshot = new QueryModel<Student>(aggregateRebuilder);
var eventBroker = Substitute.For<IDomainEventBroker>();
Guid studentId;
using (var unitOfWork = new UnitOfWork(factStore, eventBroker, new SystemClock()))
{
var repository = new Repository<Student>(snapshot, unitOfWork);
var student = Student.Create("Fred", "Flintstone");
studentId = student.Id;
repository.Add(student);
unitOfWork.Complete();
}
using (var unitOfWork = new UnitOfWork(factStore, eventBroker, new SystemClock()))
{
var repository = new Repository<Student>(snapshot, unitOfWork);
var student = repository.GetById(studentId);
student.FirstName.ShouldBe("Fred");
student.LastName.ShouldBe("Flintstone");
}
}
示例4: DetailBookController
public DetailBookController(Views.Book.BookDetailsView view, ReadOnlyContext context, int bookID, int userID)
{
this.userID = userID;
this.bookID = bookID;
_context = context;
_detailBookView = view;
_booksRepository = context.GetRepository<DataInterface.Entities.Copy>();
_leasesRepository = context.GetRepository<DataInterface.Entities.Lease>();
_usersRepository = context.GetRepository<DataInterface.Entities.User>();
_reservationsRepository = context.GetRepository<DataInterface.Entities.Reservation>();
selectedBook = _booksRepository.GetById(bookID);
var userBorrowedBooks = _leasesRepository.GetByQuery(x => x.Copy.Book.Id == bookID);
var userBookingBooks = _reservationsRepository.GetByQuery(x => x.ReservedCopy.Book.Id == bookID);
Views.Book.BookDetailsView example = new Views.Book.BookDetailsView(selectedBook, userBorrowedBooks, userBookingBooks);
if (_context.CurrentUser.Role == DataInterface.Enums.Role.Reader)
{
Return.Visible = false;
Title.Enabled = false;
Author.Enabled = false;
ISBN.Enabled = false;
PublishingYear.Enabled = false;
Publisher.Enabled = false;
Format.Enabled = false;
}
_detailBookView = example;
Return.Click += ReturnBook_Click;
Borrow.Click += Borrow_Click;
_detailBookView.Show();
}
示例5: CategoriesShouldBeReturnedNested
public void CategoriesShouldBeReturnedNested()
{
using (new TransactionScope())
{
var connectionStringProvider = new ConnectionStringProvider("<my connection string>");
var dataContextProvider = new DataContextProvider(connectionStringProvider);
// first insert a new graph into the database
var categoryRepository = new Repository<Category>(dataContextProvider);
// use the object graph created by the mock category repository
var root = MockRepositoryBuilder.CreateCategoryRepository().GetRootCategory();
// add the root into the real database
categoryRepository.InsertOnSubmit(root);
categoryRepository.SubmitChanges();
// try to get the root again (note we need the actual id because we don't want the real root,
// which will have a different graph of categories, from the database)
var rootFromDb = categoryRepository.GetById(root.CategoryId);
MockRepositoryBuilder.AssertCategoryGraphIsCorrect(rootFromDb);
}
}
示例6: AddNewsWhenNewsIsAddedToDbShouldReturnNews
public void AddNewsWhenNewsIsAddedToDbShouldReturnNews()
{
//Arange -> prepare the objects
var repo = new Repository<Models.News>(new NewsContext());
var news = new Models.News()
{
Id = 1,
Title = "title 1",
Content = "content 1",
PublishedData = DateTime.Now
};
//Act -> perform some logic
repo.Add(news);
repo.SaveChanges();
//Assert -> validate the results
var newsFromDb = repo.GetById(news.Id);
Assert.IsNotNull(newsFromDb);
Assert.AreEqual(news.Title, newsFromDb.Title);
Assert.AreEqual(news.Content, newsFromDb.Content);
Assert.AreEqual(news.PublishedData, newsFromDb.PublishedData);
Assert.IsTrue(newsFromDb.Id != 0);
}
示例7: fetch
//public static void PrintUsage(IEnumerable<ICommandFactory> availableCommands)
// {
// Console.WriteLine("List of Commands:");
// foreach(var command in availableCommands)
// Console.WriteLine("{0}", command.CommandDescription);
// }
public static IRavenEntity fetch(IRavenEntity entity)
{
Repository repo = new Repository();
var entityToReturn = repo.GetById(entity);
if (entityToReturn != null) { return entityToReturn; }
else { return null; }
}
示例8: Should_update_entity_using_single_context
public void Should_update_entity_using_single_context()
{
Order toUpdate = null;
try
{
// Get original -- Arrange
using (var context = new RepositoryTest())
{
var repo = new Repository<Order>(context);
toUpdate = repo.GetById(10337);
// alter property and then update -- Act
toUpdate.ShipName = "abc";
repo.Update(toUpdate);
}
// Requery db to Assert that data updated
using (var context = new RepositoryTest())
{
var repo = new Repository<Order>(context);
var original = repo.GetById(10337);
Assert.AreEqual("abc", original.ShipName);
}
}
finally
{
// Clean up the data so that its in the correct state
TestScriptHelper.ResetShipName();
}
}
示例9: TestAddressHandler
public void TestAddressHandler()
{
Guid id = Guid.NewGuid();
Guid companyId = Guid.NewGuid();
Guid countryId = Guid.NewGuid();
Guid cityId = Guid.NewGuid();
IMessageBus messageBus = ServiceMediator.Bus;
messageBus.Send(new AddressCommands.Create(id, Owner.Company, companyId));
messageBus.Send(new AddressCommands.ChangeCountry(id, countryId));
messageBus.Send(new AddressCommands.ChangeCity(id, cityId));
Repository<Address> repository = new Repository<Address>(ObjectFactory.Create<IEventStore>());
Address address = repository.GetById(id);
Assert.AreEqual(Owner.Company, address.State.Owner);
Assert.AreEqual(countryId, address.State.CountryId);
Assert.AreEqual(cityId, address.State.CityId);
AddressFacade facade = new AddressFacade(ObjectFactory.Create<IReadModelStore>());
GetAddressResponse response = facade.GetAddress(new GetAddressRequest {AddressId = id});
Assert.IsNotNull(response);
Assert.IsNotNull(response.Address);
Assert.AreEqual(id, response.Address.AddressId);
GetAddressListResponse searchResponse = facade.GetAddressList(new GetAddressListRequest {Filter = "qwerty"});
Assert.IsNotNull(searchResponse);
Assert.IsTrue(searchResponse.AddressList == null || searchResponse.AddressList.Count == 0);
searchResponse = facade.GetAddressList(new GetAddressListRequest { Filter = "auna" });
Assert.IsNotNull(searchResponse);
Assert.IsTrue(searchResponse.AddressList != null && searchResponse.AddressList.Count == 1);
}
示例10: CanStoreAProduct
public void CanStoreAProduct()
{
//Database.SetInitializer(new DropCreateDatabaseAlways<CoffeeShopContext>());
long id;
using (var session = m_sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var repository = new Repository<Product>(session);
var product = new Product
{
Name = "Coffee 1",
Price = 10.4m
};
repository.MakePersistent(product);
id = product.Id;
tx.Commit();
}
using (var session = m_sessionFactory.OpenSession())
using (session.BeginTransaction())
{
var repository = new Repository<Product>(session);
Product product = repository.GetById(id);
product.Satisfy(p => p.Name == "Coffee 1" && p.Price == 10.4m);
}
}
示例11: Should_return_an_object_for_id_provided
public void Should_return_an_object_for_id_provided()
{
using (var context = new RepositoryTestDataContext())
{
var repo = new Repository<Order>(context);
Assert.IsNotNull(repo.GetById(10248));
}
}
示例12: GetById_ProductWithId1IsRequestedWithNoProductsInDb_NoProductIsReturnedFromDb
public void GetById_ProductWithId1IsRequestedWithNoProductsInDb_NoProductIsReturnedFromDb()
{
using (var context = new CashRegisterContext())
{
var uut = new Repository<Product>(context);
var result = uut.GetById((long)1);
Assert.That(result, Is.EqualTo(null));
}
}
示例13: Should_throw_InvalidOperationException_if_invalid_id_provided
public void Should_throw_InvalidOperationException_if_invalid_id_provided()
{
using (var context = new RepositoryTestDataContext())
{
var repo = new Repository<Order>(context);
Assert.Throws<InvalidOperationException>(() => repo.GetById(1));
}
}
示例14: Here
public ActionResult Here(int locationId)
{
// Get the data
IRepository repository = new Repository(new CheckInDatabaseContext());
var location = repository.GetById<Location>(locationId);
if (location == null)
{
return new HttpNotFoundResult();
}
var username = HttpContext.User.Identity.Name;
var user = repository.Query<ApplicationUser>().SingleOrDefault(u => u.UserName == username);
if (user == null)
{
return new HttpNotFoundResult();
}
// make a new check in
var checkIn = new CheckIn();
checkIn.User = user;
checkIn.Location = location;
checkIn.Time = DateTime.Now;
repository.Insert(checkIn);
// check to see if this user meets any achievements
var allCheckins = repository.Query<CheckIn>().Where(c => c.User.Id == user.Id);
var allAchievements = repository.Query<Achievement>();
var allLocationIds = repository.Query<Location>().Select(l => l.Id);
// two in one day?
if (!allAchievements.Any(a => a.Type == AchievementType.TwoInOneDay) && allCheckins.Count(c => EntityFunctions.TruncateTime(c.Time) == DateTime.Today) > 2)
{
var twoInOneDay = new Achievement { Type = AchievementType.TwoInOneDay, User = user, TimeAwarded = DateTime.Now };
repository.Insert(twoInOneDay);
}
// all locations?
var hasAll = false;
foreach (var testLocationId in allLocationIds)
{
hasAll = hasAll || allCheckins.Any(c => c.Location.Id == testLocationId);
}
if (!allAchievements.Any(a => a.Type == AchievementType.AllLocations) && hasAll)
{
var allLocations = new Achievement { Type = AchievementType.AllLocations, User = user, TimeAwarded = DateTime.Now };
repository.Insert(allLocations);
}
// some day we'll have hundreds of achievements!
repository.SaveChanges();
return RedirectToAction("Index");
}
示例15: A_SetUpCountryRepo
public virtual void A_SetUpCountryRepo()
{
using (var context = new MainContext())
{
//Get the country.
var myCountryRepo = new Repository<Country>(context);
MyCountryTest = myCountryRepo.GetById(1);
}
}