ASP.Net MVC 删除包含外键约束的记录

3

我在我的asp.net MVC应用程序中遇到了删除外键约束的问题。从阅读如何删除具有外键约束的记录?,我知道需要编写某种代码来处理删除操作。

我目前拥有以下代码:

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

然而,OnModelCreating出现错误,表示在覆盖受保护的继承成员时无法更改访问修饰符,这是因为我认为正在使用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个回答

2

OnModelCreating方法使用了protected访问修饰符,当你重写它时,你需要保持访问修饰符为protected:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接