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

提前致谢

4

1 回答 1

34

It depends on what you're going to do with the columns. If you have foreign key columns like AddressId, you probably have some Address entities that you want to relate to your Xyz entities. You need to decide how the entites relate to each other, and configure the mapping you want between them.

You will need a navigation property either in your Address class, or your Xyz class, otherwise there isn't anything to bind the foreign key to, and your foreign ID columns would just be treated as normal columns (which is fine, if that's what you want).

So, if your were to add a navigation property to your Xyz entity

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;
}

You could configure the mapping by doing something along these lines (it will vary depending on the relationship:

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.
    }
}

I haven't tried using spatial types and EF, but I'd start here: http://msdn.microsoft.com/en-us/data/hh859721.aspx

There's a wealth of information on mapping configurations on the getting started with EF pages: http://msdn.microsoft.com/en-us/data/ee712907 try "Fluent API - Configuring/Mapping Properties & Types"

There's also a slightly abridged explanation of the different association types here: Code First: Independent associations vs. Foreign key associations?

于 2013-09-15T12:22:31.870 回答