0

We have a MS SQL SERVER table structure like such:

Table Org {
  Id Int
  Name Varchar(50)
}

Table Request {
  Id Int
  Name Varchar(50)
  OrgId int Not Null
}

Our Models look like this:

public class Org
{
     public int Id { get; set;}
     public string Name { get; set;}
     public List<Request> Requests { get; set;}
}

public class Request
{
     public int Id { get; set;}
     public string Name { get; set;}
     public int OrgId { get; set;}
}

And our configuration is like such:

public class RequestConfiguration : EntityTypeConfiguration<Request>
{
    public RequestConfiguration()
    {

        HasRequired(o => o.Org)
           .WithMany(o => o.Requests)
           .HasForeignKey(o => o.OrgId);
     }
}

Every time I go to make a new Request Instance, and assign an Org to it, it creates a NEW record in the Org table - no matter what. This is on the same dbcontext. I've tried various mappings in the configuration, all result in the same behavior. What am I doing wrong?

Thanks!

4

1 回答 1

0

您必须告诉 EFOrg已经存在。否则 EF 将假定Org是新的并且您希望将其插入数据库。可以通过Org从数据库加载现有的或将其附加到上下文来做到这一点:

using (var context = new MyContext())
{
    var newRequest = new Request();

    var existingOrg = new Org { Id = existingOrgId };
    context.Orgs.Attach(existingOrg);
    // or instead of the previous two lines:
    // var existingOrg = context.Orgs.Find(existingOrgId);

    newRequest.Org = existingOrg;

    context.Requests.Add(newRequest);
    context.SaveChanges();
}

这将插入一个新Request的,外键OrgId引用现有的Org.

实际上,因为您有一个外键属性,所以您根本不需要Org实例。您可以只设置 FK 值:

    var newRequest = new Request();

    newRequest.OrgId = existingOrgId;

    context.Requests.Add(newRequest);
    context.SaveChanges();
于 2013-05-09T15:28:46.950 回答