Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF核心多对多复合键_C#_Entity Framework_Asp.net Core_Entity Relationship_Ef Fluent Api - Fatal编程技术网

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();