简体   繁体   English

实体框架最佳实践

[英]Entity Framework best practice

I am developing ASP.NET (WebForms) app and using EntityFramework. 我正在开发ASP.NET(WebForms)应用程序并使用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. 此表具有到customers_addresses和customers_phones表的ForeignKey。 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. 对于案例1,我得到一个实体,其中只有“name”列映射到用户到db。对于案例2,我得到了另一个实体,其中包含其他表之间的所有数据和连接。

Now I was wondering if only single entity (number 2) would be good for both cases. 现在我想知道是否只有单个实体(数字2)对两种情况都有好处。

What's the best practice with EF ? 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 由于您将使用Linq to Entities进行所有查询,因此请确保您仅从实体中选择客户名称,而不是整个实体本身

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. 这样,您在后端仍然可以使用轻量级SQL查询,但是您不会使用不必要的“专用”实体来污染您的模型。

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. 此外,如果您正在使用延迟加载,那么您不必担心EF加载任何相关的实体信息,除非您确实需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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