使用EF CTP4映射反向关系.... [英] Mapping Inverse relationships using EF CTP4....
本文介绍了使用EF CTP4映射反向关系....的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用CTP 4支持的实体框架4中的代码优先方法在我的项目中实现数据访问层。
I am trying to implement data access layer in my project using code first approach in Entity Framework 4 which is supported by CTP 4.
首先,我决定尝试使用Northwind示例数据库。
To start with I decided to try my hands on Northwind sample database.
我创建了2个类"类别"。和"产品"如下所示。
I created 2 classes "Category" and "Product" as following.
public class Category : EntityBase
{
public virtual string CategoryName { get; set; }
public virtual string Description { get; set; }
public double? TestColumn { get; set; }
private ICollection<Product> _products;
public virtual ICollection<Product> Products
{
get { return _products; }
set { _products = value; }
}
public Category()
{
_products = new List<Product>();
}
}
public class Product : EntityBase
{
public string ProductName { get; set; }
public int SupplierID { get; set; }
public string QuantityPerUnit { get; set; }
public Decimal UnitPrice { get; set; }
public Int16 UnitsInStock { get; set; }
public Int16 UnitsOnOrder { get; set; }
public Int16 ReorderLevel { get; set; }
public bool Discontinued { get; set; }
public virtual Category Category { get; set; }
}
对于这些类,我创建了映射类来覆盖默认约定,如下所示。
For these classes I created mapping classes to override the default conventions as following.
public
class
CategoryMapping : EntityConfiguration<Category>
{
public
CategoryMapping()
{
HasKey(c => c.Id);
Property(c => c.Id).IsIdentity();
Property(c => c.CategoryName).IsRequired().HasMaxLength(15);
Property(c => c.Description);
HasMany(c => c.Products).WithRequired(p =>p.Category);
MapSingleType(c => new
{ CategoryID = c.Id, c.CategoryName, c.Description}).ToTable("dbo.Categories"
);
}
}
public
class
ProductMapping : EntityConfiguration<Product>
{
public
ProductMapping()
{
HasKey(p => p.Id);
Property(p => p.Id).IsIdentity();
Property(p => p.ProductName).IsRequired().HasMaxLength(40);
Property(p => p.SupplierID);
Property(p => p.QuantityPerUnit).HasMaxLength(20);
Property(p => p.UnitPrice);
Property(p => p.UnitsInStock);
Property(p => p.UnitsOnOrder);
Property(p => p.ReorderLevel);
Property(p => p.Discontinued);
HasRequired<Category>(p => p.Category).WithMany(c => c.Products);
MapSingleType(p => new
{ ProductID = p.Id, p.ProductName, CategoryID = p.Category.Id, p.SupplierID, p.QuantityPerUnit, p.UnitPrice, p.UnitsInStock, p.UnitsOnOrder, p.ReorderLevel, p.Discontinued }).ToTable("dbo.Products"
);
}
}
推荐答案
您可能希望切换延迟加载,以便在尝试访问时从数据库中检索给定产品的类别;
It looks like you probably want to switch lazy loading on so that the Category for a given product is retrieved from the database when you try to access it;
objectContext.ContextOptions.LazyLoadingEnabled = true;
这篇关于使用EF CTP4映射反向关系....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文