• 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

  • 相关阅读:
    WPF的布局--DockPanel
    WPF的布局--StackPanel
    C#中的不可空类型转为可空类型
    linux下安装nodejs及npm
    HTML DOM 事件对象 ondragend 事件
    pc端页面在移动端显示问题
    css设置文字上下居中,一行文字居中,两行或多行文字同样居中。
    超简单的gif图制作工具
    Git创建与合并分支
    props default 数组/对象的默认值应当由一个工厂函数返回
  • 原文地址:https://www.cnblogs.com/season2009/p/2825889.html
Copyright © 2020-2023  润新知