2

I have an object, I will call it Thing, that has a many-to-one relationship with another object, I will call it Person. How can I add Thing using DbContext without duplicating the associated Person. Thing has a foreign key to Person called PersonID.

public class Thing
{
  public long ID { get; set; }
  public long PersonID { get; set; }
}

public class Person
{
  public long ID { get; set; }
}

I tried this:

context.Things.Add(newThing);
context.SaveChanges();

I also tried to do this:

Person person = new Person() { ID = newThing.PersonID };
context.Persons.Attach(person);
context.Things.Add(newThing);
context.SaveChanges();
4
  • Saying how you create newThing and populate its properties would likely make it much easier to answer the question. Commented Jun 30, 2011 at 23:04
  • How does it matter. For example, Thing newThing = new Thing() { PersonID = 1 }. What currently happens is EF will create another Person in the database with identical properties to the Person with ID=1 (of course the ID is incremented since it is the PK). Commented Jun 30, 2011 at 23:13
  • 1
    The whole context matters because what you are saying is not correct in the general case. If you just set the FK property and leave the navigation property null (you have a navigation property, right?) you don't get duplicated records. You have a special situation which causes this behaviour and I'm just asking for more context to get any idea what could be the reason. Commented Jun 30, 2011 at 23:39
  • @Slauma's comment above helped me out: It reminded me that I had set the navigation property on one of my objects which was causing all sorts of problems when I tried to re-attach it later on. Commented Nov 20, 2012 at 12:44

1 Answer 1

3

Not sure if I understand the question correctly but try:

context.Entry(Person).State = System.Data.EntityState.Unchanged;

This tells EF that the entity is unchanged and hence will not attempt to save it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.