2011-10-20 48 views
1

我一直负责移植旧的应用程序来MVC 3,想先用EF的代码复制其现有的数据库模式。当前的代码库中散布着硬编码的SQL命令,因此我提出的模型必须与当前系统期望的“兼容”。我知道我可以使用EF的Database First来做到这一点,但现有的模式非常简单,我认为没有理由不先使用代码,因为我们希望有一个坚实的基础来构建,因为我们正在从旧的硬编码数据库迁移出去互动。一对一的映射

我需要的波苏斯样子:

public class Owner 
{ 
    [Key] 
    public Guid Owner_Id { get; set; } 

    // Properties 
    public string ContactName { get; set; } 
    public string PhoneNumber { get; set; } 
    public string Email { get; set; } 

    // Navigational properties 
    public virtual ICollection<Plant> Plants { get; set; } 
} 

public class Plant 
{ 
    [Key] 
    public Guid Plant_Id { get; set; } 

    // Properties 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Zip { get; set; } 

    // Foreign Keys 
    public Guid Owner_Id { get; set; } 

    // Navigational properties 
    public virtual Owner Owner { get; set; } 
    public virtual License License { get; set; } 
} 

public class License 
{ 
    [Key] public Guid License_Id { get; set; } 

    // Properties 
    public int Total { get; set; } 
    public int Users { get; set; } 
    public string Key { get; set; } 

    // Foreign Keys 
    public Guid Plant_Id { get; set; } 

    // Navigational properties 
    public virtual Plant Plant { get; set; } 
} 

它让我在试图创建的背景下,这个错误:

“无法确定类型“之间的关联的主要终点许可证“和”工厂“,这个关联的主要结局必须使用关系流畅API或数据注释来显式配置。”

我认识到,工厂应该有一个可为空FK参照License_Id,并且该许可证不应该有一个Plant_Id FK。但这些都是我处理过的卡片。 EF正在尝试做什么?

回答

1
public class Plant 
{ 
    public Guid PlantID { get; set; } 
    public virtual License License { get; set; } 
} 

public class License 
{ 
    // No need to have a PlantID foreign key since the foreign key. 
    public Guid LicenseID { get; set; } 
    public virtual Plant Plant { get; set; } 
} 

在流畅的API(在你的上下文类):

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Plant>().HasOptional(p => p.License).WithRequired(l => l.Plant); 

唯一的降级是,你实际上定义了一个0或1。 (可以在代码中处理,但仍然...)有关一对一关系的更多信息,请查看Entity Framework Code First One to One Relationship

1

尝试在许可证

// Foreign Keys 
public Guid Plant_Id { get; set; } 

// Navigational properties 
[ForeignKey("Plant_Id")] 
public virtual Plant Plant { get; set; } 

加入,让它知道这是外键,同为其它外键。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Plant>() 
      .HasOptional(e => e.License) 
      .WithOptionalPrincipal(e => e.Plant); 

    } 
+0

现在我收到一个新错误:“System.Data.Edm.EdmAssociationEnd::Multiplicity is is在'License_Plant'关系中的角色'License_Plant_Source'中无效。因为依赖角色属性不是关键属性,所以相关角色的多重性的上界必须是“*”。不知道最后的乱码是怎么回事...... – Stevoman

+0

这是相反的。 – Birey

+0

仍然没有去,回到原来的错误。 :( – Stevoman