Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 如何在实体框架5的0:0..N中添加记录_C# 4.0_Entity Framework 5 - Fatal编程技术网

C# 4.0 如何在实体框架5的0:0..N中添加记录

C# 4.0 如何在实体框架5的0:0..N中添加记录,c#-4.0,entity-framework-5,C# 4.0,Entity Framework 5,我们有一个MS SQL SERVER表结构,如下所示: Table Org { Id Int Name Varchar(50) } Table Request { Id Int Name Varchar(50) OrgId int Not Null } public class RequestConfiguration : EntityTypeConfiguration<Request> { public RequestConfiguration()

我们有一个MS SQL SERVER表结构,如下所示:

Table Org {
  Id Int
  Name Varchar(50)
}

Table Request {
  Id Int
  Name Varchar(50)
  OrgId int Not Null
}
public class RequestConfiguration : EntityTypeConfiguration<Request>
{
    public RequestConfiguration()
    {

        HasRequired(o => o.Org)
           .WithMany(o => o.Requests)
           .HasForeignKey(o => o.OrgId);
     }
}
我们的模型如下所示:

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;}
}
公共类组织
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共列表请求{get;set;}
}
公共类请求
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共整数组织{get;set;}
}
我们的配置如下:

Table Org {
  Id Int
  Name Varchar(50)
}

Table Request {
  Id Int
  Name Varchar(50)
  OrgId int Not Null
}
public class RequestConfiguration : EntityTypeConfiguration<Request>
{
    public RequestConfiguration()
    {

        HasRequired(o => o.Org)
           .WithMany(o => o.Requests)
           .HasForeignKey(o => o.OrgId);
     }
}
公共类请求配置:EntityTypeConfiguration
{
公共请求配置()
{
HasRequired(o=>o.Org)
.WithMany(o=>o.Requests)
.HasForeignKey(o=>o.OrgId);
}
}
每次我去创建一个新的请求实例,并将一个组织分配给它时,它都会在组织表中创建一条新记录——不管发生什么。这是在同一个dbcontext上。我在配置中尝试了各种映射,所有映射都会导致相同的行为。我做错了什么


谢谢

您必须告诉EF组织已经存在。否则,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();
}
这将插入一个新的
请求
,外键为
OrgId
,参考现有的
组织

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

    var newRequest = new Request();

    newRequest.OrgId = existingOrgId;

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

啊,是的,是从Orgs那边错过了附件!非常感谢。