2011-08-16 77 views
0

我不能映射后续的数据库结构:EF 4.1流利的映射问题与一到一个关系

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

我想要一个标志(LogoID是唯一键)的一个媒体。按照我的流利的映射:

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. 

我怎么能映射呢?

+0

实体框架不支持唯一键,因此您不能映射唯一键上的一对一关系。唯一的办法就是用@Eranga描述的一对多关系作弊。 –

回答

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为您生成映射。

+0

嗨,Eranga,这不适合我,遵循异常:System.Data.UpdateException:更新条目时发生错误。详情请参阅内部例外。 ---> System.Data.SqlClient.SqlException:列名'Sponsor_ID'无效。 –

+0

@Thiago你可以发布你的模型类。你还没有配置一些其他的财产(类似于我给出的答案) – Eranga

+0

我的问题已更新,非常感谢您的关注... –