views:

104

answers:

1

I have a parent object book, and a property of that object is publisher. Everytime I ad a book, it is adding a new publisher, even if the publisher already exists. Can someone tell me how to add the book and instead of adding the publisher again, just reference an existing one? The code i am using is below... Thanks in advance!

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);
A: 

The problem is in the line:

Publisher = new Publisher() { PublisherID = 1 }

Object context doesn't know that this is existing publisher. It is newly created entity so Object context will perform insert operation. You have to say object context that the publisher object is not newly created. One way to do that is modification of your Add method:

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();
}
Ladislav Mrnka
I tried this, but got the following error: "The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'Blah.Publisher'." Any ideas?
zaph0d