C# EF 4.1保存记录为查找表创建记录

C# EF 4.1保存记录为查找表创建记录,c#,frameworks,entity,ef-code-first,C#,Frameworks,Entity,Ef Code First,这是我的课 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; } } 当我保存一个活动时,它会创建一个新位置,即使它已经存在。如

这是我的课

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; }
}

当我保存一个活动时,它会创建一个新位置,即使它已经存在。如何设置它以使其使用现有位置?

将Key属性添加到Activity.ID,就像对Location.Name所做的一样

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

通过上下文加载现有的
位置
,并将其用作
活动的属性值

例如:


另一种方法是在添加活动之前将位置附加到上下文:

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();
}
它节省了从数据库获取位置的时间

另一个选项(需要更改模型)是向Activity类公开location的外键:

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; }
}
然后,您可以简单地指定FK值:

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

在这种情况下,请保留
Location
导航属性
null

我认为这不是问题所在。EF 4.1有一个约定,如果没有使用[key]属性,它会自动为名为ID或ID的属性分配密钥。谢谢!这是可行的,但我不明白为什么我要做这个检查。Location类/表只有一个字段,它是键。@aboes81如果您不手动加载或附加,EF会将
Location
对象视为新对象。
using(var context = new MyDbContext())
{
    var activity = new Activity { Personnel = "Foo", LocationName = "MyName" };
    context.Activities.Add(activity);
    context.SaveChanges();
}