C# EF核心多对多复合键
我目前正在尝试执行以下操作:C# EF核心多对多复合键,c#,entity-framework,asp.net-core,entity-relationship,ef-fluent-api,C#,Entity Framework,Asp.net Core,Entity Relationship,Ef Fluent Api,我目前正在尝试执行以下操作: modelBuilder.Entity<Tag>() .HasKey(bc => new { bc.Type, bc.Name }); modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post)
modelBuilder.Entity<Tag>()
.HasKey(bc => new { bc.Type, bc.Name });
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.Tags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId)
.HasPrincipalKey(x => x.Id);
Post.cs及其相关多对多表:
public class Post
{
public int Id { get; set; }
public ICollection<PostTag> Tags { get; set; }
}
public class PostTag
{
public int TagId { get; set; }
public Tag Tag { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
}
(tags
是一个与PostTag.Tag的签名相匹配的对象,由于它是动态构建的,因此它不是关系型的)
我觉得这可能是我的问题,但我似乎无法解决它。请原谅我没有理解你的问题,你的
类型
是标记类型
类型,你使用它和名称
作为联合主键,可以吗?
modelBuilder.Entity<Tag>()
.HasKey(bc => new { bc.Type, bc.Name });
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.Tags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId)
.HasPrincipalKey(x => x.Id);
post.Tags = tags.Select(x => new PostTag
{
Tag = x
}).ToList();