Gelo
Gelo

Reputation: 67

How do I add new object, which has properties that are already in database?

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

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

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

  • You can get Model1 from database (what you have now) and it will be loaded to context with Unchanged state
  • You can tell Entity Framework that it's not new entity

Second 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

Related Questions