我有一个父对象簿,该对象的属性是发布者。每当我做一本书时,即使发布者已经存在,它也会添加一个新的发布者。有人能告诉我如何添加该书,而不是再次添加发布者,只需引用现有的发布者?我正在使用的代码如下...在此先感谢!EF4代码中的1对1对象关系代码优先
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);
我试过这个,但是得到了下面的错误:“ObjectStateManager不包含一个ObjectStateEntry,它引用了一个'Blah.Publisher'类型的对象。”有任何想法吗? – 2010-09-03 03:56:11