首页 新闻 搜索 专区 学院

EFCore 多对多配制映射问题

0
[已解决问题] 解决于 2017-11-12 23:34

具体错误信息:Cannot remove key {'Id'} from entity type 'Category' because it is referenced by a foreign key in entity type 'CategoryProducts'. All foreign keys must be removed or redefined before the referenced key can be removed.”

刘发源的主页 刘发源 | 菜鸟二级 | 园豆:220
提问于:2017-11-06 11:46
< >
分享
最佳答案
0

最终问题已经找到由于doman的BaseEntiy Id {set } 为Private,我改为public就没有问题了

刘发源 | 菜鸟二级 |园豆:220 | 2017-11-12 23:34
其他回答(1)
0
public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public ICollection<Category> Categories { get; set; }
} 
public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<Book> Books { get; set; }
}
public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
} 

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
}

public class BookCategory
{
    public int BookId { get; set; }
    public Book Book { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BookCategory>()
        .HasKey(bc => new { bc.BookId, bc.CategoryId });

    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Book)
        .WithMany(b => b.BookCategories)
        .HasForeignKey(bc => bc.BookId);

    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Category)
        .WithMany(c => c.BookCategories)
        .HasForeignKey(bc => bc.CategoryId);
}

你参考一下上面这个配置,Reference

BUTTERAPPLE | 园豆:2950 (老鸟四级) | 2017-11-06 11:53

谢谢回复,问题已找到,是在写baseEntity的时候把id的set属性设置了私有了,所以才出这个问题

支持(0) 反对(0) 刘发源 | 园豆:220 (菜鸟二级) | 2017-11-12 23:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册