Mar*_*ano 5 c# entity-framework entity-framework-core
我是 Entity Framework Core 的新手,对下一种情况有疑问。
我有三个对象,如下所示:
TableA {
public int Id {get; set;}
public string Name {get; set;}
public IList<TableA_TableB> TableA_TableBList {get; set;}
}
TableA_TableB {
public int Id {get; set;}
public TableA TableA {get; set;}
public int TableAId {get; set;}
public TableB TableB {get; set;}
public int TableBId {get; set;}
}
TableB {
public int Id {get; set;}
public string Name {get; set;}
public IList<TableA_TableB> TableA_TableBList {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我使用 Fluent Api 来映射关系:
builder
.HasOne(a_b => a_b.TableA)
.WithMany(a => a.TableA_TableBList)
.HasForeignKey(a_b => a_b.TableAId);
builder
.HasOne(a_b => a_b.TableB)
.WithMany(b => b.TableA_TableBList)
.HasForeignKey(a_b => a_b.TableBId);
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我尝试在 TableA 中插入新值以及 TableA_TablesB 中的新值时,但 TableB 中存在现有值。我使用的代码是:
var entity = (TableA)tableADto; //From controller and convert to TableA using explict operator
entity.TableA_TableBList = new List<TableA_TableBList>();
entity.TableA_TableBList.Add(new TableA_TableB()
{
TableAId = entity.Id,
TableBId = 1 // I put a fix value just to test
});
_tableARepository.Add(entity);
_unitOfWork.Commit();
Run Code Online (Sandbox Code Playgroud)
当我打电话时SaveChanges(),显示此错误:
INSERT 语句与 FOREIGN KEY 约束“FK_TableA_TableB_TableB_TableBId”冲突。
冲突发生在数据库“tenantteste”、表“dbo.TableB”、列“Id”中。
我尝试获取 TableB 值并添加导航属性(TableB 属性)。但是,我保存时并没有建立关系,而是增加了价值。
我已经阅读了 stackoverflow 上的文档和一些问题,我相信使用 FK 应该可以工作,但它不起作用。
我不知道我做错了什么。
有几件事是错误的。首先,您的链接表不应该有代理键。这是文档中的多对多示例:
class MyContext : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId);
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
https://learn.microsoft.com/en-us/ef/core/modeling/relationships#other-relationship-patterns
请注意,链接实体具有复合键 (PostId,TabId)。
| 归档时间: |
|
| 查看次数: |
13613 次 |
| 最近记录: |