我有一个实体框架核心的问题。我有2个模型:category.cs
public int Id { get; set; }
[DisplayName("Category | ")]
[Required(ErrorMessage = "Category Name is Required")]
public string CategoryName { get; set; }
和LibraryItem.cs
public int Id { get; set; }
[DisplayName("Category Id")]
[Required(ErrorMessage = "Category Id is Required")]
public int CategoryId { get; set; }
public Category Category { get; set; }
[Required(ErrorMessage = "Title is Required")]
public string Title { get; set; }
[DisplayName("Author, Speaker or Director")]
[Required(ErrorMessage = "Creator of the media is required")]
public string Author { get; set; }
public int? Pages { get; set; }
[DisplayName("DVD or Audiobook Length")]
public int? RunTimeMinutes { get; set; }
[DisplayName("Available to borrow")]
public bool IsBorrowable { get; set; }
[DisplayName("Name of Borrower")]
public string Borrower { get; set; }
[DisplayName("Date of the Borrow")]
public DateTime? date { get; set; }
[DisplayName("Type of Media")]
[Required(ErrorMessage = "Type of Media is Required")]
public string Type { get; set; }
LibraryItem有一个外键CategoryId,它是Category表的主键。我想用相同的外键添加两个项目。所以这两个项目属于同一类别。但当我尝试添加具有相同CategoryId的另一个时,会出现以下错误
cannot insert duplicate key row in object
有人知道是什么导致了这个问题吗?多谢!
问题是您创建了一对一的关系,但您需要一对多
您必须修复您的类别类:
public int Id { get; set; }
[DisplayName("Category | ")]
[Required(ErrorMessage = "Category Name is Required")]
public string CategoryName { get; set; }
[InverseProperty(nameof(Library.Category))]
public virtual ICollection<LibraryItem> LibraryItems {get; set:}
修复后,您将不得不再次进行迁移
您必须通过在每个类上添加导航属性,让EF知道这两个实体以一对多的关系相关:
public class Category {
...
public virtual ICollection<LibraryItem> LibraryItems {get; set;}
}
public class LibraryItem {
...
[DisplayName("Category Id")]
[Required(ErrorMessage = "Category Id is Required")]
public int CategoryId { get; set; }
public Category Category { get; set; }
}
如果添加了导航属性,则可以使用Fluent API手动配置DbContext的OnModelCreating方法中的关系
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LibraryItem>()
.HasOne(l => l.Category)
.WithMany(c => c.LibraryItems);
}