entity-framework - 使用Fluent API的 Entity Framework 代码优先映射外键

标签 entity-framework ef-code-first entity-framework-4.1 fluent-interface

我有一个用户可以有多个地址的情况。因此,我的用户类上有一个ICollection。但我也希望用户能够选择默认地址。因此,我完成了以下操作:

public class User 
{
    public int Id { get; set; }
    public int? DefaultAddressId { get; set; }
    [ForeignKey("DefaultAddressId")]
    public virtual Address DefaultAddress { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    //properties were removed for purpose of this post
}

我想完全删除public virtual Address DefaultAddress { get; set; },保留DefaultAddressId并使用Fluent API对其进行映射,因为当前的设置引起了很多麻烦(在该类以及其他具有类似设置的类中)。那么可以使用流利的api来做到这一点吗?

更新:
地址类当前没有对User类的任何引用,它是单向关系。但是,是的,一个地址仅属于一个用户,它不是多对多关系。这是地址类别:
public class Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Details { get; set; }
    public virtual Area Area { get; set; }
}

最佳答案

我个人将外键关系从User移到Address,并在地址类上添加了IsDefaultAddress属性。

public class Address
{
    public int Id { get; set; }

    // This property marks the FK relation
    public virtual User User { get; set; }

    public string Name { get; set; }
    public string Details { get; set; }
    public virtual Area Area { get; set; }

    // This property signals whether this is the user's default address
    public bool IsDefaultAddress { get; set; }
}

EF知道它需要Foreign KeyAddress之间的User关系。

这将大大简化您的模型。也就是说,当然,如果一个地址只能属于一个用户(如Slauma在评论中所要求的)。

关于entity-framework - 使用Fluent API的 Entity Framework 代码优先映射外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489569/

相关文章:

entity-framework - 您如何确保首先对 EF 代码中的表关系启用级联删除?

c# - 将 IQueryable 转换为 BindingList

c# - 无效操作异常 : Cannot use table 'xxxx1' for entity type 'xxxx2' since it is being used for entity type 'xxxx1'

entity-framework - 在 viewbag 中传递查询结果

asp.net-mvc - 使用 Entity Framework 保存更改/更新数据集中的现有对象,而不必分别设置每个属性

entity-framework - Entity Framework 4.1 Fluent API 中带有连接表和可选关系的一对多

c# - 了解代码优先虚拟属性

c# - 如何在 Entity Framework 中获取列的默认值

c# - Entity Framework 中可重用的 linq 选择查询

c# - 每个表只允许一个标识列