2012-11-03 112 views
0

我有以下实体类Code。它存储了不同种类的类别 - 我所需要的数据以创建许多小表格,例如用户类别,费用类别,地址类型,用户类型,文件格式等用实体框架代码优先定义外键约束

public class Code 
{ 
    public int Id { get; set; } 
    public string CodeType { get; set; } 
    public string CodeDescription { get; set; } 


    public virtual ICollection<Expense> Expenses { get; set; } 
    public virtual ICollection<Address> Addresses { get; set; } 
        : 
        : // many more 

} 

Expense看起来是这样的:

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

    public int CategoryId { get; set; } 
    public virtual Code Category { get; set; } 

    public int SourceId { get; set; } 

    public double Amount { get; set; } 
    public DateTime ExpenseDate { get; set; } 
} 

通过上述类定义,我已经建立了1:许多关系在CodeExpense之间使用CategoryId映射。

我的问题是,我想将Expense中的SourceId字段映射到Code对象。这意味着,Expense对象将包含

public Code Source { get; set; } 

如果我用这个,在运行时我得到循环依赖错误。

有人可以帮忙吗?

+0

你能发布你的映射吗? – khellang

回答

0

您将需要禁用两个关系中的至少一个(或两者)上的级联删除。 EF通过惯例为两种关系启用级联删除,因为两者都是要求,因为外键属性不可为空。但是,SQL Server不接受多个到两个关系引入的同一个表上的级联删除路径。这是你例外的原因。

必须覆盖以流利的API的约定:

public class Code 
{ 
    public int Id { get; set; } 
    //... 
    public virtual ICollection<Expense> Expenses { get; set; } 
    //... 
} 

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

    public int CategoryId { get; set; } 
    public virtual Code Category { get; set; } 

    public int SourceId { get; set; } 
    public virtual Code Source { get; set; } 
    //... 
} 

映射用流利的API;

modelBuilder.Entity<Expense>() 
    .HasRequired(e => e.Category) 
    .WithMany(c => c.Expenses) 
    .HasForeignKey(e => e.CategoryId) 
    .WillCascadeOnDelete(false); 

modelBuilder.Entity<Expense>() 
    .HasRequired(e => e.Source) 
    .WithMany() 
    .HasForeignKey(e => e.SourceId) 
    .WillCascadeOnDelete(false); 
+0

谢谢百万Slauma - 它的奇迹!你摇滚......我花了这么多时间,几乎已经想到改变某种方法。再次感谢! – Sandeep