EF中的一对多导航属性

时间:2015-11-23 11:10:03

标签: c# entity-framework one-to-many

有没有人知道如何使用Entity Framework正确实现一对多导航属性。

假设我有以下两种模式:

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; }
}

我希望模型保持原样 - 即我不想将BookId或Book本身引入Review类。 我有两个基础表:

Book:
Id, Title

Review:
Id, Text, Rating, BookId

我在代码中创建了一些映射:

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

我错过了什么?感谢

0 个答案:

没有答案