2014-12-13 37 views
0

我尝试实现与实体框架6的1..0关系。我使用实例关联。我试图重复从网络和论坛的例子,但不知何故它不适合我。请帮忙。EF 6.0中的空联合实体Fluent Api

实体:

public class CustomerWithFk : Item // Item contains Id 
    { 
     public string Name { get; protected set; } 
     public virtual City City { get; set; }  // relation property. Can be 1 or 0 
     public virtual Product Product { get; set; } 
     public decimal Money { get; protected set; } 
    } 

    public class City : Item 
    { 
     public string Name { get; protected set; } 
    } 

映射:

public CityMap() 
{ 
    ToTable("Cities"); 
    HasKey(c => c.Id); 
} 

public CustomerFkAssosiationMap() 
{ 
    ToTable("Customers"); 
    HasKey(c => c.Id); 

    HasRequired(g => g.City) 
     .WithRequiredDependent(); 

    HasRequired(g => g.Product) 
       .WithRequiredDependent() 
       .Map(x => x.MapKey("ProductId")); 
} 

数据库表: enter image description here

SQL事件探查器给我enxt SQL请求:

SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[Money] AS [Money], 
    [Extent1].[CityId] AS [CityId], 
    [Extent1].[ProductId] AS [ProductId] 
    FROM [dbo].[Customers] AS [Extent1] 

所以,我在这里没有看到任何连接从城市或产品加载数据。 其结果是空: enter image description here

我尝试了不同的映射选项,如:HasOptional,WithRequiredPrincipal,试图客户广告载体添加到市(虽然这是不正确的,城市没有了解一下客户) 没有帮助。辅助实体始终为空。 我错在哪里?

回答

1

问题是你没有包括相关的对象。使用Include尝试这样的事情:

var list = context.CustomerWithFk 
        .Include("City") 
        .Include("Product"); 

这告诉你要拉回顾客城市和产品一起实体框架。如果您有兴趣,请参阅以下文章:http://msdn.microsoft.com/en-us/data/jj574232.aspx

编辑:您还可以使延迟加载(根据您的意见,我相信这是你所追求的)加入该对上下文:

context.ContextOptions.LazyLoadingEnabled = true; 

了解更多关于延迟加载这里:http://msdn.microsoft.com/en-us/library/vstudio/dd456846(v=vs.100).aspx

+0

谢谢。但是有什么办法不使用像Include这样的显式命令并且在后台使用FK?我确信,昨天,在一些映射实验中,我用正确的结果填充了属性而不用调用Include。 它看起来像我非常接近解决方案,但盲目,看不到我的错误... – 2014-12-13 18:59:52

+1

请参阅编辑。我相信你正在寻找懒加载。 – Dean 2014-12-13 20:05:11