具有一对一关系的EF 4.1流畅映射问题

时间:2011-08-16 03:34:11

标签: entity-framework entity-framework-4.1 ef-code-first

我无法映射以下数据库结构:

http://i.stack.imgur.com/iJmIq.png

我想要一个媒体的Logo(LogoID是UniqueKey)。按照我的流利映射:

public class SponsorMap : EntityTypeConfiguration<Sponsor>
{
    public SponsorMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);
        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(255);
        this.Property(t => t.Description)
            .IsRequired();
        this.Property(t => t.SiteAddress)
            .HasMaxLength(300);
        this.Property(t => t.TwitterName)
            .HasMaxLength(20);
        this.Property(t => t.FacebookAddress)
            .HasMaxLength(300);
        // Relationships
        //this.HasOptional(t => t.Logo);
        this.HasOptional(t => t.Logo)
            .WithOptionalDependent();
    }
}

关注模特:

   public class Sponsor{
    public Sponsor(){this.Goods = new List<Goods>();} public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string SiteAddress { get; set; }
    public string TwitterName { get; set; }
    public string FacebookAddress { get; set; }
    public virtual ICollection<Goods> Goods { get; set; }
    public virtual Media Logo { get; set; }
}
    public class Media{
    public Media(){}
    public int ID { get; set; }
    public string Path { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public virtual Goods Good { get; set; }
    public virtual MediaType MediaType { get; set; }
}

我的测试中出现以下错误:

Test method 

Inove.Kenquer.Data.Tests.UserRepositoryTest.When_Save_User_With_Action_Get_Same_Actions_From_DB threw exception: 
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: **Invalid column name 'Logo_ID'.**
-----------------------------------------
MediaMap has no mapping to Sponsor.

我该如何映射?

1 个答案:

答案 0 :(得分:2)

你可以像这样映射它。

public SponsorMap()
{

    //other mappings

    HasOptional(sponsor => sponsor.Logo)
           .WithMany()
           .Map(sponsor => sponsor.MapKey("LogoID"));

    HasMany(sponsor => sponsor.Goods)
           .WithOptional(good => good.Sponsor)
           .Map(x => x.MapKey("SponsorID"));
}

修改

您需要映射所有导航属性。我根据您提供的信息在SponsorGood之间添加了映射。

阅读一些关于如何使用流畅映射的文章(例如:ADO.NET team blog)。

您可以使用EF power tools为您生成映射。