【发布时间】:2021-06-18 12:33:02
【问题描述】:
我正在尝试在我的数据库中以多对多关系播种数据,但我无法进行迁移。我正在使用 Entity Framework Core 5.0.6。
这是我的模型:
总体思路是:一个Tag可以属于多个Topic。一个主题可以有多个标签。
标签.cs:
public class Tag
{
public int Id { get; set; }
// [...]
public ICollection<Topic> Topics { get; set; }
public List<TopicTag> TopicTags { get; set; }
}
主题.cs
public class Topic
{
public int Id { get; set; }
// [...]
public ICollection<Tag> Tags { get; set; }
public List<TopicTag> TopicTags { get; set; }
}
还有 TopicTag.cs
public class TopicTag
{
public int TopicId { get; set; }
public Topic Topic { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
这是我在OnModelCreating 在我的ApplicationDbContext 中的内容:
// [...]
// Configuring relation
modelBuilder.Entity<Topic>()
.HasMany(topic => topic.Tags)
.WithMany(x => x.Topics)
.UsingEntity<TopicTag>(
j => j
.HasOne(tt => tt.Tag)
.WithMany(t => t.TopicTags)
.HasForeignKey(t => t.TagId),
j => j
.HasOne(tt => tt.Topic)
.WithMany(t => t.TopicTags)
.HasForeignKey(t => t.TopicId),
j => { j.HasKey(t => new {t.TopicId, t.TagId}); }
);
modelBuilder.Entity<Tag>()
.HasMany(tag => tag.Topics)
.WithMany(x => x.Tags)
.UsingEntity<TopicTag>(
j => j
.HasOne(tt => tt.Topic)
.WithMany(t => t.TopicTags)
.HasForeignKey(t => t.TopicId),
j => j
.HasOne(tt => tt.Tag)
.WithMany(t => t.TopicTags)
.HasForeignKey(t => t.TagId),
j => { j.HasKey(t => new {t.TopicId, t.TagId}); }
);
// [...]
// Seeding data
for (int t = -1; t >= -4; t--)
{
builder.Entity<Tag>().HasData(new Tag()
{
Id = t,
Name = "tag" + t
});
}
for (int y = -1; y >= -10; y--)
{
builder.Entity<Topic>().HasData(new Topic()
{
Id = y,
// [...]
});
}
// Finally joining them together
for (int y = -1; y >= -10; y--)
{
builder.Entity<TopicTag>().HasData(new TopicTag()
{
TopicId = y,
TagId = -1 * ((y % 4) + 1)
});
}
因此,当我尝试创建新迁移时,我收到此错误:
尝试保存更改时,“TopicTag.TagId”的值未知。这是因为该属性也是关系中的主体实体未知的外键的一部分。
说实话,我不明白错误消息的含义。 TopicTag.TagId 是已知的,因为我在 for 循环中创建新的 TopicTag 时指定它。此外,我在那里引用的所有 id 都是以前创建的。
【问题讨论】:
-
你用的是什么数据库?
-
@Serge MsSQL Server 2017
标签: c# entity-framework entity-framework-core