ASP.NET MVC 3 EF代码优先 - FOREIGN KEYS的问题

时间:2012-01-19 12:12:27

标签: c# foreign-keys ef-code-first

在使用Entity Framework Code First时,我遇到SQL Server创建外键约束的问题。

这是我的情景。我正在构建一个应用程序,允许我们针对任何系统记录故障单,并自动将故障单分配给相关人员。

我们有服务,可以有很多类别。类别可以有许多子类别。可以将服务台人员分配到服务,类别或子类别。

以下是我的课程:

Service.cs

public class Service
{
    [Key]
    public int ServiceID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<Subcategory> Subcategories { get; set; }
    public virtual ICollection<HelpDeskMember> LinesOfSupport { get; set; }
}

Category.cs

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    [ForeignKey("Service")]
    public int ServiceID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public virtual Service Service { get; set; }
    public virtual ICollection<Subcategory> Subcategories { get; set; }
    public virtual ICollection<HelpDeskMember> LinesOfSupport { get; set; }
}

Subcategory.cs

public class Subcategory
{
    [Key]
    public int SubcategoryID { get; set; }
    [ForeignKey("Service")]
    public int ServiceID { get; set; }
    [ForeignKey("Category")]
    public int CategoryID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public virtual Service Service { get; set; }
    public virtual Category Category { get; set; }
    public virtual ICollection<HelpDeskMember> LinesOfSupport { get; set; }       
}

最后是HelpDeskMember.cs

public class HelpDeskMember
{
    public int HelpDeskMemberID { get; set; }
    public string Name { get; set; }
    public bool Admin { get; set; }
    public bool Available { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? LastLogin { get; set; }
    public DateTime? DeletedDate { get; set; }
    public DateTime? DeletedBy { get; set; }

    public virtual ICollection<Service> Services { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<Subcategory> Subcategories { get; set; }

}

初始化数据库时,我收到以下错误消息:

在表'子类别'上引入FOREIGN KEY约束'Subcategory_Service'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。 无法创建约束。查看以前的错误。

我猜测问题在于我如何定义Key和ForeignKey。任何帮助赞赏。感谢。

1 个答案:

答案 0 :(得分:1)

根据您的需要而定。您可以在实体配置中使用WillCascadeOnDelete(false) 1或全局删除OneToManyCascadeDeleteConvention 2

可以使用ModelBuilder输入参数在OnModelCreating中设置两者。