EF sqlite数据库表的级联删除

问题描述 投票:0回答:1

有人可以帮我为DeleteBehavior.ClientCascade编写正确的代码吗? 我有两个类

Account
Schedule
定义如下(
Account
可以有许多
Schedule
对象):

 public class Account : IdentityUser
        { 
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
    
            public List<Schedule> Schedules { get; set; }
        }
        public class Schedule
        {
                public string AccountAccountId { get; set; }
                public int ScheduleId { get; set; }
                public DateTime Date { get; set; }
        }

... and the context

     public class DataContext : IdentityDbContext<Account>
        {
            public DbSet<Account> Accounts { get; set; }
            public DbSet<Schedule> Schedules { get; set; }
            public DataContext(IConfiguration configuration, DbContextOptions options) : base(options)
            {
                Configuration = configuration;
            }
    
            protected override void OnConfiguring(DbContextOptionsBuilder options)
            {
                // connect to sqlite database
                options.UseSqlite(Configuration.GetConnectionString("WebApiDatabase"));
            }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                //modelBuilder.Entity<Account>().HasMany(e => e.RefreshTokens).WithOne(e => e.Account).IsRequired();
    
                modelBuilder.Entity<Schedule>()
                .HasOne(b => b.Account)
                .HasMany(a => a.Schedules) <--- Error
                .OnDelete(DeleteBehavior.ClientCascade); <--- Error
            }
        }

我正在关注这篇文章链接,但在尝试执行以下操作时,我的

DataContext
遇到错误:

modelBuilder.Entity<Schedule>()
        .HasOne(b => b.Account)<--- error
        .HasMany(a => a.Schedules) 
        .OnDelete(DeleteBehavior.ClientCascade); 
c# sqlite cascading-deletes
1个回答
0
投票

本文档不完整。也许你应该首先尝试这个https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration。 要定义一对多关系。您需要创建如下所示的 Schedule 类

    public class Schedule
    {
        public string AccountAccountId { get; set; }
        public int ScheduleId { get; set; }
        public DateTime Date { get; set; }
        public Account? Account { get;set; }
    }

此处使用

Account?
使外键 AccounId 可为空。
通常使用“s”代表“schedule”,并且您的日程表类现在有一个“Account”字段。 然后你可以定义一对多关系的使用

            modelBuilder.Entity<Schedule>()
                .HasOne(s => s.Account)
                .WithMany(a => a.Schedules);

            modelBuilder.Entity<Account()
                .HasMany(a => a.Schedules)
                .WithOne(s => s.Account);

他们有相同的结果。必须首先在实体后面使用

Has..
,然后使用
With
。您的代码实际上使用了 2
Has...
方法。

如果您没有将

.OnDelete(DeleteBehavior.ClientCascade);
添加到
?
以使其可为空,则
Account?
可能会变成错误。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.