这是我的课程
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; }
}
当我保存活动时,它会创建一个新的位置,即使它已经存在。如何设置它以使用现有的位置?
答案 0 :(得分:1)
通过上下文加载现有的Location
,并将其用作Activity
例如:
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();
}
答案 1 :(得分:0)
将Key属性添加到Activity.ID,就像您对Location.Name
一样public class Activity
{
[Key]
public int ID {get;set;}
public string Personnel { get; set; }
public Location Location { get; set; }
}
答案 2 :(得分:0)
另一种方法是在添加活动之前将位置附加到上下文:
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类:
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
。