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
Entity framework 在实体框架5上使用fluent api映射实体_Entity Framework_C# 4.0_Orm_Code First_Lambda - Fatal编程技术网

Entity framework 在实体框架5上使用fluent api映射实体

Entity framework 在实体框架5上使用fluent api映射实体,entity-framework,c#-4.0,orm,code-first,lambda,Entity Framework,C# 4.0,Orm,Code First,Lambda,我有个问题 我有两张桌子: 主体表是具有客户依赖性的用户 逆向工程代码首先生成如下类: public class User { public User() { this.Customers = new List<Customer>(); } ... public virtual ICollection<Customer> Customers { get; set; } } public

我有个问题

我有两张桌子:

主体表是具有客户依赖性的用户

逆向工程代码首先生成如下类:

public class User
{
    public User()
    {
        this.Customers = new List<Customer>();          
    }

    ...

    public virtual ICollection<Customer> Customers { get; set; }

}

public class Customer
{
    public Customer()
    {
    }

    ...

    public int UserID { get; set; }
    public virtual User User { get; set; }

}
因为关系是一对零或一

原始映射如下所示:

// Relationships
        this.HasRequired(t => t.User)
            .WithMany(t => t.Customers)
            .HasForeignKey(d => d.UserID);
修改后的映射如下:

this.HasRequired(t => t.User)
            .WithOptional(t => t.Customer)
            .Map(m => m.MapKey("UserID"));
对吗? 如果没有,该映射将如何进行

谢谢。

不,不正确

您可以做的最好的事情(假设您可以更改数据库架构)是从
Customer
表中删除
UserID
外键,然后在数据库中创建两个主键之间的关系,以便
Customer.CustomerID
是关联中的外键

然后,逆向工程应自动创建预期的一对一关系,如下所示:

public class Customer
{
    public int CustomerID { get; set; }
    public virtual User User { get; set; }
    //...
}

public class User
{
    public int UserID { get; set; }
    public virtual Customer Customer { get; set; }
    //...
}

//...

this.HasRequired(t => t.User)
    .WithOptional(t => t.Customer);
如果无法更改数据库架构,最好只从
User
类中删除集合
ICollection Customers
,并保持一对多的关系

原因是EF只支持共享主键一对一关联,而不支持外键一对一关联。(后者只能通过删除集合来“伪造”,但从EF的角度来看,它仍然是一对多。)

您可以在此处阅读有关EF一对一关联及其限制的更多信息:


Hi@Slauma,我不明白为什么要删除客户表的外键。我在这个例子中所做的是他的第二个选择。@Gus:不,这不是他的第二个选择。他的第二个选项(“一对一外键关联”)使用
with many()
,而不是
with optional
。这是与已删除集合的一对多关系,即仅一个导航属性。此外,如果有名为
UserID
的属性,则不能使用
MapKey(“UserID”)
。然后必须使用
HasForeignKey
,如Mortezza的示例所示。
public class Customer
{
    public int CustomerID { get; set; }
    public virtual User User { get; set; }
    //...
}

public class User
{
    public int UserID { get; set; }
    public virtual Customer Customer { get; set; }
    //...
}

//...

this.HasRequired(t => t.User)
    .WithOptional(t => t.Customer);