Reputation: 321
I have a problem with Entity Framework Core. I have 2 models: Category.cs
public int Id { get; set; }
[DisplayName("Category | ")]
[Required(ErrorMessage = "Category Name is Required")]
public string CategoryName { get; set; }
And 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 has a Foreign key of CategoryId, which is the Primary key for the Category table. I wanna add two items with the same foreign key. So the two items are within the same Category. But when I try to add another one with the same CategoryId I get this error
cannot insert duplicate key row in object
Does anyone know what might be causing this problem? Many thanks!
Upvotes: 2
Views: 676
Reputation: 11
You have to let EF know that these two entities are related in a one to many relationship by adding the navigation properties on each class:
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; }
}
If you add the navigation properties, you can use the Fluent API to manually configure relationships inside your DbContext's OnModelCreating method
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LibraryItem>()
.HasOne(l => l.Category)
.WithMany(c => c.LibraryItems);
}
Upvotes: 1
Reputation: 43850
The problem is that you created one-to-one relation, but you need one-to-many
You have to fix you Category class:
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:}
After fixing you will have to make a migration again
Upvotes: 2