简体   繁体   中英

Entity Framework best practice

I am developing ASP.NET (WebForms) app and using EntityFramework. I was wondering what is the best practice of using entities. Create few entities for whole database or create many entities for specialized purposes ?!

Example case is this: I have customers table. This table have ForeignKey to customers_addresses and customers_phones tables. I got two cases on this dataset

  1. Autocomplete customer name
  2. Show user details

For case 1 I got one entity which have only the "name" column mapped to user to db For case 2 I got another entity which have all data and connections between other tables.

Now I was wondering if only single entity (number 2) would be good for both cases.

What's the best practice with EF ?

I don't see a reason, in your case, to have a specialized entity for the autocomplete scenario. Since you'll be using Linq to Entities for all your querying, just make sure you are selecting just the Customer Name from the entity, instead of the entire entity itself

from Customer cust in ent.Customers
select new {
    CustomerName = cust.CustomerName
};

That way you still have lightweight SQL query on the backend, but you're not polluting your models with unnecessary, "specialized" entities.

In addition, if you're using lazy loading then you don't have to worry about EF loading any related entity information unless you actually need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM