实体框架,代码优先,违反多重约束

时间:2014-02-24 13:25:57

标签: entity-framework ef-code-first fluent-entity-framework

我想让一个User类包含一个书籍列表和一个可选的收藏书。在下面调用SaveChanges()时,我收到错误消息

已成功提交对数据库的更改,但更新对象上下文时发生错误。 ObjectContext可能处于不一致状态。内部异常消息:违反了多重性约束。 “ConsoleApplication1.User_FavoriteBook”关系的“User_FavoriteBook_Target”角色具有多重性1或0..1。“}

我想要完成的是让User表有一个列存储喜欢的书的Id。我怎么能这样做?

public class User
{
    public int UserId { get; set; }
    public List<Book> Books { get; set; }
    public Book FavoriteBook { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Name { get; set; }
}

public class UserContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new UserConfiguration());
    }

public class UserConfiguration : EntityTypeConfiguration<User>
    {
        public UserConfiguration()
        {
            HasMany(e => e.Books).WithRequired().WillCascadeOnDelete();
            HasOptional(e => e.FavoriteBook).WithRequired().WillCascadeOnDelete(false);
        }
    }
}

主程序:

User user = new User();
Book book1 = new Book { Name = "book1" };
Book book2 = new Book { Name = "book2" };
user.Books.Add(book1);
user.Books.Add(book2);
user.FavoriteBook = book2;

using (UserContext context = new UserContext())
{
    context.Users.Add(user);
    context.SaveChanges();
}

0 个答案:

没有答案