2012-12-14 212 views
1

我需要在實體框架中創建關係的幫助,因爲我嘗試添加遷移時嘗試的所有內容都會給我提供錯誤,或者如果我通過了,那麼我嘗試更新數據庫並獲取有關索引的錯誤同名。與實體框架的關係問題

public class Profile 
{ 
    public Profile() 
    { 
     Environments = new HashSet<Environment>(); 
    } 

    [Key] 
    public int Id { get; set; } 

    public string VersionCreated { get; set; } 

    public string DiskLocation { get; set; } 

    public string Name { get; set; } 

    public DateTime DateTime { get; set; } 

    public virtual Product Product { get; set; } 

    public virtual Instance OriginalInstance { get; set; } 

    public virtual ICollection<Environment> Environments { get; set; } 
} 


public class Instance 
{ 
    public Instance() 
    { 
     TestResults = new HashSet<TestResult>(); 
     Environments = new HashSet<Environment>(); 
    } 

    [Key] 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public string Version { get; set; } 

    public string UserFriendlyName { get; set; } 

    public virtual Product Product { get; set; } 

    public virtual Profile LastKnownProfile { get; set; } 

    public virtual Computer Computer { get; set; } 

    public virtual ICollection<TestResult> TestResults { get; set; } 

    public virtual ICollection<Environment> Environments { get; set; } 
} 

上述類的問題是,在配置文件類和LastKnownProfile的實例類的OrginalInstance財產都應該只是外鍵的那些特定的表,他們可能會不一樣很經常。他們也可能都是空的。

我曾嘗試:

modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile); 
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance); 

這給了我一個Unable to determine the principal end of an association between the types 'EcuWeb.Data.Entities.Instance' and 'EcuWeb.Data.Entities.Profile'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.錯誤。

,並用:

modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile).WithOptional(); 
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance).WithOptional(); 

數據庫增加了一個外鍵引用回自己。

+0

看起來你想要在這兩個實體之間有一對一的關係,試着只使用其中一個映射命令:modelBuilder.Entity ().HasRequired(i => i.LastKnownProfile).WithOptional(p => p.OriginalInstance); – Rashad

+0

這是更接近,但這不是我所尋找的兩個屬性根本不相互關聯。他們幾乎每次都可能並且可能會不同。它們應該只是外鍵而不涉及其他屬性,例如。 LastKnownProfile應包含ProfileId,而OriginalInstance應包含與包含LAstKnownProfile的InstanceId不同的InstanceId。 – twreid

回答

1

...,關於個人資料類和 LastKnownProfile的實例類的OrginalInstance財產都應該只是國外 鍵那些特定的表,他們可能會不一樣很 頻繁。他們也可能都是空的。

在這種情況下,你真正想要ProfileInstance之間兩個一到多的關係,如果我不要誤會你上面的報價。這意味着許多配置文件可以具有相同的OriginalInstance,並且許多實例可以具有相同的LastKnownProfile。正確的映射是這樣的,那麼:

modelBuilder.Entity<Profile>() 
    .HasOptional(p => p.OriginalInstance) 
    .WithMany() 
    .Map(m => m.MapKey("OriginalInstanceId")); 

modelBuilder.Entity<Instance>() 
    .HasOptional(i => i.LastKnownProfile) 
    .WithMany() 
    .Map(m => m.MapKey("LastKnownProfileId")); 

MapKey該行是可選的。沒有它們,EF將使用默認名稱創建一個外鍵。

另請注意,如果「兩者都可能爲空」,則必須使用HasOptional(而不是HasRequired)。

+0

謝謝你的訣竅。 – twreid