开发者

EF 4.1 Saving record creates record for lookup table

开发者 https://www.devze.com 2023-03-18 13:41 出处:网络
Here are my classes public class Activity { public int ID {get;set;} public string Personnel { get; set; }

Here are my classes

public class Activity
{
    public int ID {get;set;}
    public string Personnel { get; set; }
    public Location Location { get; set; }
}

public class Location
{
    [Key]
    public string Name { get; set; }
}

When I save an Activity it creates a new Location, even if it al开发者_运维知识库ready exists. How do I set it up so it uses existing Locations?


Load the existing Location through the context and use that as the property value of the Activity

eg:

using(var context = new MyDbContext())
{
   var location = context.Locations.FindByKey(/* set key*/);
   var activity = new Activity(){Personnel = "Foo", Location = location};
   context.Activities.Add(activity);
   context.SaveChanges();
}


Add the Key attribute to Activity.ID, just like you have for Location.Name

public class Activity
{
    [Key]
    public int ID {get;set;}
    public string Personnel { get; set; }
    public Location Location { get; set; }
}


Another way is to attach the location to the context before adding the Activity:

using(var context = new MyDbContext())
{
    var location = new Location { Name = "MyName" };
    context.Locations.Attach(location);

    var activity = new Activity { Personnel = "Foo", Location = location };
    context.Activities.Add(activity);
    context.SaveChanges();
}

It saves you to fetch the location from the DB.

Another option (which requires to change the model though) is to expose the foreign key for location to the Activity class:

public class Activity
{
    public int ID {get;set;}
    public string Personnel { get; set; }
    [ForeignKey("Location")]
    public string LocationName { get; set; }
    public Location Location { get; set; }
}

Then you can simply assign the FK value:

using(var context = new MyDbContext())
{
    var activity = new Activity { Personnel = "Foo", LocationName = "MyName" };
    context.Activities.Add(activity);
    context.SaveChanges();
}

Leave the Location navigation property null in this case.

0

精彩评论

暂无评论...
验证码 换一张
取 消