ASP.Net MVC删除具有FK约束的记录

时间:2016-04-02 10:10:13

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我的asp.net MVC应用程序有一个问题,删除了一个外键约束。从阅读How to delete a record with a foreign key constraint?开始,我知道我需要使用某种形式的代码来处理删除。

我目前的内容如下

   public override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Supplier>()
            .HasOptional(j => j.Agreement)
            .WithMany()
            .WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);
    }

然而,OnModelCreating生成错误cannot change access modifiers when overriding protected inherited member这是因为我相信我正在使用ApplicationUser和IdentityRole。

我可以解决这个问题吗?我需要放置代码吗?我最初认为我需要将其放入我的身份模型中,如下所示,但认为这是错误的。

namespace Mark_MVC.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

    }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("Mark_MVC", throwIfV1Schema: false)
    {

    }

    public override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Supplier>()
            .HasOptional(j => j.Agreement)
            .WithMany()
            .WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);
    }

    public static ApplicationDbContext Create()
    {

        return new ApplicationDbContext();
    }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Supplier> Suppliers { get; set; }
    public DbSet<Agreement> Agreements { get; set; }
    public DbSet<Plan> Plans { get; set; }
    public DbSet<TimeSheet> TimeSheets { get; set; }
    public DbSet<CustomerPlan> CustomerPlans { get; set; }
}

}

请有人帮忙

非常感谢

1 个答案:

答案 0 :(得分:2)

OnModelCreating具有受保护的访问修饰符,当您覆盖它时,您必须保持访问修饰符受保护:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //your code here
}