1

我有一个父对象 book,该对象的属性是 publisher。每次我为一本书做广告时,它都会添加一个新的出版商,即使出版商已经存在。有人能告诉我如何添加这本书,而不是再次添加出版商,只需引用现有的吗?我正在使用的代码如下...在此先感谢!

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);
4

3 回答 3

0

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

你应该做一个 fetch 方法,像这样 - 从上下文中获取你想要的出版商(例如,id = 1) - 将返回的对象设置为你的新书对象的出版商 - 上下文应该为你整理其余的。当你保存这本书时。(无需弄乱对象状态管理器)

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

于 2013-01-23T13:56:43.403 回答
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);
于 2011-01-12T18:47:55.563 回答
0

问题在于:

Publisher = new Publisher() { PublisherID = 1 }

对象上下文不知道这是现有的发布者。它是新创建的实体,因此对象上下文将执行插入操作。您必须说发布者对象不是新创建的对象上下文。一种方法是修改您的 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();
}
于 2010-08-26T21:53:13.613 回答