[英]Entity Framework - Database View or Joins in Linq to Entities
I have a database table with many lookup tables: 我有一个包含许多查找表的数据库表:
OrderType
ShippingType
etc.
My Order table is referencing each one of these tables: 我的订单表引用了这些表中的每一个:
Order
OrderID
OrderTypeID
ShippingTypeID
I am using the Entity Framework as my data access layer. 我使用实体框架作为我的数据访问层。 I have a page that needs to display information for an Order. 我有一个页面需要显示订单的信息。 I am struggling to figure out the best/right way to use these entities. 我正在努力找出使用这些实体的最佳/正确方法。
My page should be displaying the data like: 我的页面应该显示如下数据:
Order #1000000 订单#1000000
Shipping Type: UPS 运输类型:UPS
Order Type: Online 订单类型:在线
Etc Type: Etc. 等等类型:等。
Is it better to create a view in the database that brings back the data I need and then add it to my entity model, and just use that directly so I don't have to write joins in my queries? 最好在数据库中创建一个视图,它带回我需要的数据,然后将其添加到我的实体模型中,并直接使用它,这样我就不必在查询中编写连接了吗? Or is it better to create an intermediate class like so: 或者更好的是创建一个这样的中间类:
class OrderView
{
public int OrderNumber { get; set; }
public string OrderType { get; set; }
public string ShippingType { get; set; }
}
var order = from o in db.Orders
join ot in db.OrderTypes on o.OrderTypeID equals ot.OrderTypeID
join st in db.ShippingTypes on o.ShippingTypeID equals st.ShippingTypeID
select new OrderView
{
OrderNumber = o.OrderNumber,
ShippingType = st.Description,
OrderType = ot.Description
};
What is the better way here? 这里有什么更好的方法?
You don't need join
, per se. 你本身不需要join
。 What you can do is use Navigation Properties
for OrderType
and ShippingType
in order to access them without the need for joins. 您可以使用OrderType
和ShippingType
Navigation Properties
,以便在不需要连接的情况下访问它们。 You'll have something like: 你会有类似的东西:
var order = from o in db.Orders
select new OrderView
{
OrderNumber = o.OrderNumber,
ShippingType = o.ShippingType.Description,
OrderType = o.OrderType.Description
};
I don't see any advantage to doing this in a view. 我认为在视图中这样做没有任何好处。
You can use Linq-to-entities. 您可以使用Linq到实体。 I usually switch to SQL or View when I have something which I can't write in L2E (like Common table expression and hiearchical queries) or when L2E performance is bad. 当我有一些我无法在L2E中编写的内容(如公用表表达式和层次结构查询)或L2E性能不佳时,我通常会切换到SQL或View。 If you do not have these problems you should be happy with L2E. 如果您没有这些问题,您应该对L2E感到满意。
Btw. 顺便说一句。 your query can be rewritten without joins - damn @Craig was faster. 您的查询可以在没有连接的情况下重写 - 该死的@Craig更快。
Views can be good for several reasons: 由于以下几个原因,视图可能很好:
Do whatever leads to more understandable code. 做任何事都会导致更易理解的代码。
using a database view can hinder the SQL optimizer's ability to get you the best execution plan. 使用数据库视图可能会阻碍SQL优化器为您提供最佳执行计划的能力。 so if the EF-generated query is not a horror (use SQL Profiler to make sure!) i`d go for EF. 因此,如果EF生成的查询不是一个恐怖(使用SQL事件探查器来确保!)我会去EF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.