2010-08-26 76 views
1

我有一个父对象簿,该对象的属性是发布者。每当我做一本书时,即使发布者已经存在,它也会添加一个新的发布者。有人能告诉我如何添加该书,而不是再次添加发布者,只需引用现有的发布者?我正在使用的代码如下...在此先感谢!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); 

回答

0

的问题是在该行:

Publisher = new Publisher() { PublisherID = 1 } 

对象上下文不知道,这是现有的出版商。它是新创建的实体,所以对象上下文将执行插入操作。您必须说出发布者对象不是新创建的对象上下文。要做到这一点的方法之一是您的添加方法的调整:

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(); 
} 
+0

我试过这个,但是得到了下面的错误:“ObjectStateManager不包含一个ObjectStateEntry,它引用了一个'Blah.Publisher'类型的对象。”有任何想法吗? – 2010-09-03 03:56:11

0

它可以通过确保发布者添加图书实体之前附着到出版商方面解决这个问题(这样就知道这是从的DbContext发布者不,它需要一个新的补充(再次))

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

的问题是在这条线 出版商=新发行(){的publisherId = 1}

你应该做一个获取方法,以便像这样的 - 从上下文获取想要的发布者(例如,其中id = 1) - 将返回的对象设置为新图书对象的发布者 - 上下文应该为您挑选剩余的内容。当你保存这本书。 (不需要与对象状态管理器混淆)

祝你好运,如果你不能得到这个工作,把它的一些代码,我会帮助你,虽然它。