MVC Code First中的惯例(约定)

主健

如果Model中包含如下字段(不区分大小写,按优先级列出),则会当做主健

  1. 'Id'

  2. [type name]Id

  参考:http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.conventions.idkeydiscoveryconvention(v=vs.103).aspx

 

外健

采用如下方法定义外健

View Code
public class Department
{
    // Primary key
    public int DepartmentID { get; set; }
    public string Name { get; set; }
 
    // Navigation property
    public virtual ICollection<Course> Courses { get; set; }
}
 
public class Course
{
    // Primary key
    public int CourseID { get; set; }
 
    public string Title { get; set; }
    public int Credits { get; set; }
 
    // Foreign key
    public int DepartmentID { get; set; }
 
    // Navigation properties
    public virtual Department Department { get; set; }
}

当一个Model有两个外健时,如

public class Comment
    {
        public int CommentId { get; set; }

        #region Foreign key & Navigation property
        // Foreign key
        public int VideoId { get; set; }
        // Navigation property
        public virtual Video Video { get; set; }

        // Foreign key
        public int AccountId { get; set; }
        // Navigation property
        public virtual Account Account { get; set; }
        #endregion
    }

程序会报类似如下错误:

Introducing FOREIGN KEY constraint 'SalesOrder_Invoices' on table 'Invoices' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

原因分析:

针对一对多关系,EF自动设置级联删除。

解决办法:

    public class StarObjectContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
       modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   //取消级联删除设置
            base.OnModelCreating(modelBuilder);
        }
    }

也可以单独取消某个Model的设置

modelBuilder.Entity<...>()
            .HasRequired(...)
            .WithMany(...)
            .HasForeignKey(...)
            .WillCascadeOnDelete(false);

 

参考资料:

http://stackoverflow.com/questions/5532810/entity-framework-code-first-defining-relationships-keys

http://msdn.microsoft.com/en-us/data/jj679962

posted @ 2012-12-20 10:59  Season2009  阅读(431)  评论(0编辑  收藏  举报