EF4 Code First中的1对1对象关系

时间:2010-08-26 18:59:12

标签: entity-framework parent-child code-first

我有一个父对象书,该对象的属性是发布者。每当我刊登一本书时,即使发布商已经存在,它也会添加新的发布商。有人可以告诉我如何添加图书而不是再次添加发布者,只需引用现有的图书吗?我正在使用的代码如下......提前致谢!

public class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime CreateDate { get; set; }

    public virtual Publisher Publisher { get; set; }
}

public class Publisher
{
    public int PublisherID { get; set; }
    public string Address { get; set; }
}

public class SqlCEDataStore : DbContext
{
    public DbSet<Book> Books { get; set; }
    public DbSet<Publishers> Publishers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.IncludeMetadataInDatabase = false;
    }
}

public class TimeSinkRepository : IRepository<Book>
{
    private static SqlCEDataStore context = new SqlCEDataStore();

    public int Add(Book entity)
    {
        context.Books.Add(entity);
        return context.SaveChanges();
    }
}

var book = new Book()
{
      Title = "New Title",
      Description = "New Description",
      CreateDate = DateTime.Now,
      Publisher = new Publisher() { PublisherID = 1 }
};

var repository = new BookRepository();
var result = repository.Add(book);

3 个答案:

答案 0 :(得分:0)

问题在于:

Publisher = new Publisher() { PublisherID = 1 }

对象上下文不知道这是现有的发布者。它是新创建的实体,因此Object上下文将执行插入操作。您必须说不是新创建发布者对象的对象上下文。一种方法是修改Add方法:

public int Add(Book entity)
{
  context.Books.Add(entity);

  // 0 means new one, other values mean existing one
  if (entity.Publisher.PublisherID > 0)
  {
    context.ObjectStateManager.ChangeObjectState(entity.Publisher, EntityState.Unchanged);
  }

  context.SaveChanges();
}

答案 1 :(得分:0)

你可以通过确保在添加Book实体之前将Publisher附加到Publishers上下文来解决这个问题(这样它就知道它是dbcontext中的Publisher而不是它需要添加的新的(再次))

context.Publishers.Attach(book.Publisher); // This is only possible if the Publisher is not new
context.Books.Add(book);

答案 2 :(得分:0)

问题出在这一行 Publisher = new Publisher(){PublisherID = 1}

你应该做一个像这样的获取方法   - 从上下文中获取所需的发布者(例如,id = 1)   - 将返回的对象设置为新书对象的发布者   - 上下文应该为你排序休息。当你保存书籍。 (不需要弄乱对象状态管理器)

祝你好运,如果你不能让这个工作提出一些代码,我会帮助你。

相关问题