C# EF中的一对多导航属性

C# EF中的一对多导航属性,c#,entity-framework,one-to-many,C#,Entity Framework,One To Many,有人知道如何使用实体框架正确实现一对多导航属性吗 假设我有以下两种模型: public class Book { public string Id { get; set; } public string Title { get; set; } public ICollection<Review> Reviews { get; set; } } public class Review { public int Id { get; set; }

有人知道如何使用实体框架正确实现一对多导航属性吗

假设我有以下两种模型:

public class Book
{
    public string Id { get; set; }
    public string Title { get; set; }
    public ICollection<Review> Reviews { get; set; }
}

public class Review
{
    public int Id { get; set; }
    public string Text { get; set; }
    public int Rating { get; set; }
}
我在代码中创建了一些映射:

public class BookConfiguration : EntityTypeConfiguration<Book>
{
    public BookConfiguration()
    {
        ToTable("Book");
        HasKey(book => book.Id);
        Property(book => book.Id).HasColumnName("Id");
        Property(book => book.Title).HasColumnName("Title").IsRequired();

        HasMany(book => book.Reviews).WithRequired().Map(m => m.MapKey("BookId"));
    }
}


public class ReviewConfiguration : EntityTypeConfiguration<Review>
{
    public ReviewConfiguration()
    {
        ToTable("Review");
        HasKey(review => review.Id);
        Property(review => review.Id).HasColumnName("Id");
        Property(review => review.Text).HasColumnName("Text");
    }
}

我错过了什么?谢谢

为什么不让BookId在评论中?如果你想“正确地”做这件事,那么你可能必须这样做。你是如何试图保存这些书的?您能显示fialing代码吗?如果您不想将书籍添加到评论中,则需要在两者之间创建一个链接表。。链接表将保存Book实体的主键和Review实体的主键。不是您要寻找的确切的一对多关系,但是使用业务逻辑您可以解决这个问题。关于我上面的评论,您可以将此表命名为BookReviews,并且在您的book实体中有一个ICollection BookReviews{get;set;}。。代码中的导航将是book.BookReviews.review{…}中的foreachvar review
public class BookConfiguration : EntityTypeConfiguration<Book>
{
    public BookConfiguration()
    {
        ToTable("Book");
        HasKey(book => book.Id);
        Property(book => book.Id).HasColumnName("Id");
        Property(book => book.Title).HasColumnName("Title").IsRequired();

        HasMany(book => book.Reviews).WithRequired().Map(m => m.MapKey("BookId"));
    }
}


public class ReviewConfiguration : EntityTypeConfiguration<Review>
{
    public ReviewConfiguration()
    {
        ToTable("Review");
        HasKey(review => review.Id);
        Property(review => review.Id).HasColumnName("Id");
        Property(review => review.Text).HasColumnName("Text");
    }
}
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

InnerException: A relationship from the 'Book_Reviews' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Book_Reviews_Target' must also in the 'Deleted' state