I have trouble with adding an entity to database which contains an relation to existing object. I searched alot and couldn't find proper solution for this. I will describe this as simple as I can.
public class Store : IEntity
{
public int StoreId { get; set; }
public string StoreName { get; set; }
public virtual Address Address { get; set; }
public virtual Contractor Contractor { get; set; }
}
public class Product : IEntity
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public virtual Store Store { get; set; }
}
And in repository im adding records like this. This is generic class
public TEntity Add(TEntity entity)
{
using (var context = new TContext())
{
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
return entity;
}
}
Now when i try to add new record like this
var store = storeManager.GetBy(x => x.StoreId == 1);
var product = new Product() { ProductName = "Bananas", Store = store };
productManager.Add(product);
productManager.GetAll().ForEach(x => Console.WriteLine(x.ProductName + " " + x.Store.StoreId));
Store relation is added as new store and it get's new ID. Does someone have idea how i can solve this?
Example from database:
StoreId StoreName Address_AddressId Contractor_ContractorId
1 NULL 1 1
2 NULL 2 2
3 NULL 3 3
4 NULL 4 4
5 NULL 5 5
6 NULL 6 6
7 NULL 7 7
It's my first question on stackoverflow.