【发布时间】:2021-03-04 02:38:52
【问题描述】:
我有 2 张桌子。一个用于课程,另一个用于关键字。
这两个表具有多对多关系。所以我把另一个表设置为CourseKeywords。
public class CourseKeyword
{
public int CourseId { get; set; }
public int KeywordId { get; set; }
public virtual Course Course { get; set; }
public virtual Keyword Keyword { get; set; }
}
public class Course
{
[Key]
public int Id { get; set; }
[MaxLength(300)]
public string Title { get; set; }
[MaxLength(300)]
public string SubTitle { get; set; }
public string Body { get; set; }
public ICollection<CourseKeyword> Keywords { get; set; }
public Guid Token { get; set; }
[MaxLength(300)]
public string Photo { get; set; }
[MaxLength(300)]
public string Preview { get; set; }
public bool IsSpecial { get; set; }
}
public class Keyword
{
[Key]
public int Id { get; set; }
[MaxLength(300)]
public string Title { get; set; }
public ICollection<CourseKeyword> CourseKeywords { get; set; }
public ICollection<BlogKeyword> BlogKeywords { get; set; }
}
当我想添加带有一些新关键字的新课程时。我成功添加了课程。然后添加关键字,但是当我尝试添加CourseKeyword 对象时,在SaveChange() 它显示以下错误:
InnerException = {"INSERT 语句与 FOREIGN 冲突 KEY 约束“FK_CourseKeywords_Course_KeywordId”。冲突 发生在数据库“PandaAcademyNew”,表“dbo.Course”,列 'Id'。\r\n语句已终止。"}
当我想保存更改时会发生这种情况。我的代码在这里:
var course = _db.Course.Find(model.Id);
var keyw = _db.Keywords.Find(keyword.Id);
var key = new CourseKeyword()
{
Course = course,
Keyword = keyw
};
_db.CourseKeywords.Add(key);
_db.SaveChanges();
这是我的上下文OnModelCreating:
builder.Entity<CourseKeyword>(courseKeyword =>
{
courseKeyword.HasKey(ur => new { ur.KeywordId, ur.CourseId });
courseKeyword.HasOne(ur => ur.Course)
.WithMany(r => r.Keywords)
.HasForeignKey(ur => ur.CourseId)
.IsRequired();
courseKeyword.HasOne(ur => ur.Keyword)
.WithMany(r => r.CourseKeywords)
.HasForeignKey(ur => ur.KeywordId)
.IsRequired();
});
【问题讨论】:
-
您如何接收
Course和Keyword数据?如果您尝试使用一些现有关键字创建新课程,为什么要进行Find操作?您应该能够通过一个SaveChanges()调用来创建它。可以分享一下完整的方法吗?
标签: c# .net-core entity-framework-core