【发布时间】:2020-12-31 06:43:42
【问题描述】:
我在我的 dbcontext(ToDo, Category) 中使用流利的 api 创建了两个模型我想要实现的是,每当我创建一个新的 ToDo 对象时,CategoryId 的默认值被指定为“默认”类别的 id我之前成功创建,我仍然需要该关系是非可选的才能使用级联删除,但是如果没有在请求正文中指定,categoryid 的值始终分配为 1。
我现在遇到的问题是,当不指定 categoryid 时,只会得到一个空值。 以下是请求和随后的响应: POST 到 api/todos
{
"Context":"234234"
}
{
"id": 2,
"context": "234234",
"done": false,
"dueDate": "0001-01-01T00:00:00",
"category": null
}
public class AppDbContext : DbContext
{
public DbSet<Category> categories { get; set; }
public DbSet<ToDo> todos { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ToDo>().ToTable("TODO");
builder.Entity<ToDo>().HasKey(p => p.Id);
builder.Entity<ToDo>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<ToDo>().Property(p => p.Context).HasMaxLength(50);
builder.Entity<ToDo>().Property(p => p.Done);
builder.Entity<ToDo>().Property(p => p.DueDate);
builder.Entity<ToDo>().Property(p => p.CategoryId).HasDefaultValue(1);
builder.Entity<Category>().ToTable("CATEGORIES");
builder.Entity<Category>().HasKey(p => p.Id);
builder.Entity<Category>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();//.HasValueGenerator<InMemoryIntegerValueGenerator<int>>();
builder.Entity<Category>().Property(p => p.Name).IsRequired().HasMaxLength(30);
builder.Entity<Category>().HasMany(p => p.ToDoS).WithOne(p => p.Category).HasForeignKey(p => p.CategoryId);
builder.Entity<Category>().HasData(
new
{
Id = 1,
Name = "Default"
}
);
}
}
}
【问题讨论】:
-
您是否尝试在旧数据上实现它?我不确定它是否会产生任何影响,但在声明您在类别中有数据后尝试放置 ToDo 实体构建器。你正在迁移到这个吗?
-
不,我使用的是 inmemorydb,所以每次我重新启动应用程序时数据都会被清除,在数据播种后放置 ToDo 没有帮助
-
inmemorydb 的问题是它不检查约束,所以也许你真的没有那个数据。尝试将其切换到 SQL Lite 或 Sql 并查看它是否会引发错误。如果是,那么您确定您进行了相应的迁移吗?
-
我可以确认您的代码适用于 SQLite,但不适用于 InMemory。
标签: c# asp.net database entity-framework