williamsandonz
williamsandonz

Reputation: 16420

How to do efficient inserts?

When I insert a new object to the DB I tie it with a relationship to another, by doing another db lookup, I'd like to remove this extra step for efficiency, I.E How can I set a relationship to another using just the ID, rather than having to fetch the whole object from the DB? e.g.:

Car C = new Car();
C.Person = db.person.find(PersonID); //unnecessary lookup
//I'd like to do: C.setPersonID(personID);
db.cars.add(C);
db.saveChanges();

where model:

class Car
{
   public virtual Person Person { get; set; }
}

Upvotes: 1

Views: 93

Answers (3)

Dan
Dan

Reputation: 13343

I haven't run this to confirm, but I believe there is a Convention based ID system used by Entity Framework. This may well automatically do what you don't want to happen.

class Car
{
   public virtual Person Person { get; set; }
   public virtual Int32   PersonID { get; set; }
}

I was going to post code from the NerdDinner project where I have seen this before (http://nerddinner.codeplex.com/) but you can look it up as it is fairly attribute-laden code.

Upvotes: 0

cubski
cubski

Reputation: 3248

Assuming that its a one-to-one relationship, you could do this:

public class Car
{
    public int Id { get; set; }
    public int PersonId { get; set; }
    public Person Person { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class CarConfiguration : EntityTypeConfiguration<Car>
{
    public CarConfiguration()
    {
        HasKey(i => i.Id);
        HasRequired(i => i.Person).WithMany().HasForeignKey(i => i.PersonId).WillCascadeOnDelete(false);
    }
}

Then to add a new car with a person using only the person's Id and also assuming that the person with that Id is existing:

using (var ctx = new CarContext())
{
    var car = new Car();
    car.PersonId = 5;
    ctx.Cars.Add(car);
    ctx.SaveChanges();
}

You may find this link useful.

Upvotes: 2

Pawel
Pawel

Reputation: 31610

Use foreign keys and set the foreign key property accordingly.

Upvotes: 0

Related Questions