MVC Code First中的惯例(约定)

本文深入解析了Entity Framework中主键和外键的定义方式,包括如何在模型中正确指定主键和外键,以及在一对多关系中遇到的错误及其解决方案。通过实例代码,详细解释了如何避免并解决“FOREIGNKEY约束引入”相关的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主健

如果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

转载于:https://www.cnblogs.com/season2009/archive/2012/12/20/2825889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值