2013-01-22 27 views
0

我使用EF5.0 CF让我们考虑一下论文实体(这里简化):EF5名单物化每一个实体

public class Catalog 
{ 
    public int Id { get; set; } 
    public bool IsActive { get; set; } 
    public string Name { get; set; } 
    public ICollection<PricedProduct> Products { get; set; }  
} 

public class PricedProduct 
{ 
    public int Id { get; set; } 
    public bool IsActive { get; set; } 
    public Product Product { get; set; } 
    public Price Price { get; set; } 
} 

public class Price 
{ 
    public int Id { get; set; } 
} 

public class Product 
{ 
    public int Id { get; set; } 
    public string Name {get; set;} 
} 

他们配置了一口流利的API:

//For the Catalog entity 
ToTable("Catalog", "Catalog"); 
this.Property(t => t.Name).HasColumnType("nvarchar").HasMaxLength(100).IsRequired(); 

this.HasMany<PricedProduct>(t => t.Products).WithMany(). 
Map(mc => 
     { 
     mc.ToTable("CatalogPricedProduct", "Catalog"); 
     mc.MapLeftKey("PricedProductID"); 
     mc.MapRightKey("CatalogID"); 
     }); 

//For the PricedProduct entity 
ToTable("PricedProducts", "Catalog"); 
HasRequired(t => t.Product).WithOptional().Map(m=>m.MapKey()); 
HasRequired(t => t.Price).WithOptional().Map(m => m.MapKey()); 

//For the Product entity 
ToTable("Products", "Catalog"); 
this.Property(t => t.Name).HasColumnType("nvarchar").HasMaxLength(100).IsRequired(); 

//For the Price entity 
ToTable("Prices", "Catalog"); 

所以基本上我有一个目录,其中有N:这有两个1 N的关系与PricedProduct:1与产品关系和价格

我得到这个LINQ查询这些实体:

var qy = from cata in this.Set<Catalog>().Include("Products") 
        .Include("Products.Product") 
        .Include("Products.Price") 
        where cata.Name == "name" 
        select cata; 
return qy.FirstOrDefault(); 

只要两个PricedProduct不共享相同的产品或相同的价格,一切正常。

这意味着,在PricedProducts表中,只要产品或价格FK是“唯一的”,如果另一个PricedProduct在价格上具有相同的FK值,则PriceProduct将被正确检索和实现,例如,价格将不会加载有关PricedProduct。

我已经快速检查生成的SQL查询和它看起来很好,感觉就像EF不遂同一对象的两个实例在同一张图上?

任何人都知道该怎么做或什么是错我的代码?

非常感谢

回答

0

那是因为你对你的模型的理解不正确。如果多个PricedProduct可以有相同的Price或相同Product则无法将其映射为一个一对一的关系,但作为一个一对多(一个价格可以分配给许多价位产品 - 同样的产品)。你需要:

ToTable("PricedProducts", "Catalog"); 
HasRequired(t => t.Product).WithMany(); 
HasRequired(t => t.Price).WithMany(); 
+0

Thx拉迪斯拉夫,你是对的,我的坏 – Axel