如何在EntityTypeConfiguration类中设置外键

17

我刚开始创建EntityTypeConfiguration类并执行了以下操作

public class Xyz
{
   public int PlaceId { get; set; }

    public string  Name { get; set; }

    public DbGeography Location { get; set; }

    public int HumanTypeId { get; set; }

    public int AddressId { get; set; }
}

并且在EntityTypeConfiguration类中

 public sealed class XyzConfiguration:EntityTypeConfiguration<Xyz>
{
    public XyzConfiguration()
    {
        ToTable("Place", "dbo");
        HasKey(p => p.PlaceId);   
        Property(p => p.PlaceId)
            .HasColumnName("PlaceId")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(p => p.Name);
        Property(p => p.Location). ;
        Property(p => p.HumanTypeId);
        Property(p => p.AddressId);
    }
}

现在如何设置 DbGeography 和外键列 HumanTypeId、AddressId

提前致谢。

1个回答

34
这取决于你要如何处理这些列。如果你有像 AddressId 这样的外键列,你可能会有一些与你的 Xyz 实体相关联的 Address 实体。你需要决定实体之间的关系,并配置它们之间的映射。
你需要在你的 Address 类或者 Xyz 类中添加导航属性,否则就没有任何东西可以绑定到外键上,你的外键列就只会被视为普通列(如果这是你想要的话那就没问题)。
所以,如果你要在你的 Xyz 实体中添加一个导航属性:
public class Xyz
{
    // Your code
    public int AddressId { get; set; }
    public virtual Address MyAddress { get; set; }
}

// Your Address class
public class Address
{
    public int ID;
}
您可以通过类似以下方式配置映射(具体方式因关系而异):
public sealed class XyzConfiguration : EntityTypeConfiguration<Xyz>
{
    public XyzConfiguration()
    {
        // Your code.

        this.HasOptional(x => x.MyAddress)      // Your Xyz has an optional Address
            .WithMany()                         // Address may be owned by many Xyz objects
            .HasForeignKey(x => x.AddressId);   // Use this foreign key.
    }
}

我尚未尝试使用空间类型和EF,但我会从这里开始:http://msdn.microsoft.com/en-us/data/hh859721.aspx

在EF入门页面上有大量的映射配置信息:http://msdn.microsoft.com/en-us/data/ee712907,可以尝试查看“Fluent API-配置/映射属性和类型”

这里也有一个略微简化的不同关联类型的解释: Code First:Independent associations vs. Foreign key associations?


你能否评论使用 DbContext 配置实体和使用 EntityTypeConfiguration 的区别? - Don Cheadle
嗨,我已经有几年没有使用EF了,所以我的知识有点生疏。我不能立即回忆起如何使用DbContext配置映射,你有特定的示例吗? - Chris
1
@mmcrae 配置实体的位置并不重要。如果你喜欢在覆盖 OnModelCreating 方法中进行配置,那么你基本上需要编写相同的代码。在这种情况下,它将类似于 modelBuilder.Entity<Xyz>().Map(..... 等等。我更喜欢为每个模型单独创建文件。想象一下,如果你有100多个模型,而所有映射都写在 OnModelCreating 方法中... 代码会很长。 - Pepito Fernandez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接