Tutorial by Examples

Bad Example: var location = dbContext.Location .Where(l => l.Location.ID == location_ID) .SingleOrDefault(); return location; Since the above code is simply returning an entity without modifying or adding it, we can avoid tracking cost. Good Ex...
One problem often seen in code is loading all the data. This will greatly increase the load on the server. Let's say I have a model called "location" that has 10 fields in it, but not all the fields are required at the same time. Let's say I only want the 'LocationName' parameter of that...
Suppose we want to count how many counties are there in Texas: var counties = dbContext.States.Single(s => s.Code == "tx").Counties.Count(); The query is correct, but inefficient. States.Single(…) loads a state from the database. Next, Counties loads all 254 counties with all of the...
When using async queries, you can execute multiple queries at the same time, but not on the same context. If the execution time of one query is 10s, the time for the bad example will be 20s, while the time for the good example will be 10s. Bad Example IEnumerable<TResult1> result1; IEnumera...
If you just want to get data, but not modify anything, you can turn off change tracking and proxy creation. This will improve your performance and also prevent lazy loading. Bad Example: using(var context = new Context()) { return await context.Set<MyEntity>().ToListAsync().ConfigureAw...
Say we have Products and Categorys in a many-to-many relationship: public class Product { public Product() { Categories = new HashSet<Category>(); } public int ProductId { get; set; } public string ProductName { get; set; } public virtual ICollection&lt...

Page 1 of 1