Question

I just started to make EntityTypeConfiguration class and did following

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

and in EntityTypeConfiguration class

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

Now how to set DbGeography and foreign key columns HumanTypeId , AddressId ?

Thanks in advance

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top