保存记录为查找表创建记录

本文关键字:记录 创建 保存 查找 | 更新日期: 2023-09-27 18:01:23

以下是我的类

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

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

保存记录为查找表创建记录

通过上下文加载现有的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();
}

添加Key属性到Activity。ID,就像Location一样。名称

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

它节省了您从数据库中获取位置。

另一个选项(需要更改模型)是将location的外键公开给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