MVC3删除主表时自动删除从表中相关信息的方法

在Entities:DbContext里添加如下代码:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Account>().HasRequired(b => b.User).WithMany(a => a.Accounts).WillCascadeOnDelete(true);
            base.OnModelCreating(modelBuilder);
        }

这里Account是从表,User是主表

 public class User
    {
        [Key]
        [DisplayName("用户编号")]
        public string UserCode { get; set; }
        [DisplayName("用户账号")]
        public string UserAccount { get; set; }
        [DisplayName("用户密码")]
        public string Password { get; set; }
        public  List<Account> Accounts { get; set; }
    }
 public class Account
    {
        [Key]
        public int Id { get; set; }
        [DisplayName("编码")]
        public string UserCode { get; set; }

        [DisplayName("输入者")]
        public string Inputer { get; set; }
        public virtual User User { get; set; }
    }

 

学习交流群:364976091
上一篇:linux下find,xargs命令详解和实例


下一篇:Panopticlick揭示你不能删除cookie