Reputation: 67
I have these models(1 & 2):
public class Model1
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Model2> Model2s { get; set; }
}
public class Model2
{
public int Id { get; set; }
public virtual Model1 model1 { get; set; }
}
In database I already have record of Model1 with Id=1 and Name="SomeName".
When I'm creating new Model2 like this:
var item = new Model1 { Id=1, Name="SomeName" }
Model2 model2 = new Model2
{
model1 = item
}
Model2 doesn't reference to Model1 in database, instead, it creates new Model1 record in database.
So, my question is, can in that case make it reference to exiting record instead of how it does it right now?
I can do the following:
var item = context.Model1s.Find(1);
Model2 model2 = new Model2
{
model1 = item;
}
But it's not a good option in my case. I want to know, can I do like l did in the first example.
Upvotes: 1
Views: 80
Reputation: 236308
If you are creating new instance of Model1
then it will have Added
state and EF will not know that similar entity exists in database.
You have two options here
Model1
from database (what you have now) and it will be loaded to context with Unchanged stateSecond option means attaching entity to context
var item = new Model1 { Id=1, Name="SomeName" };
context.Model1s.Attach(item);
Model2 model2 = new Model2
{
model1 = item
}
Entity which you create manually is not tracket by context. When you attach such entity, then it will be tracked and it will have Unchanged state. You can also specify entity state manually
context.Entry(item).State = EntityState.Unchanged;
Further reading: Entity Framework Entity States
Upvotes: 1