2013-09-01 128 views
0

當添加一對多關係實體時,我得到一個InvalidCaseException。它在添加而不是SaveChanges上失敗。EF InvalidCastException一對多關係

無法轉換 類型的對象 'System.Collections.Generic.List`1 [UserAccount]' 鍵入 'UserAccount'。

據特林情況下,x的集合X的一個實例

(家長或一個實體)

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false), Serializable()] 
public class Merchant 
{ 

    /// <summary> 
    /// Standard ID 
    /// </summary> 
    [Key] 
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] 
    public int ID { get; set; } 
    [DataType(DataType.Text), MaxLength(100)] 
    /// <summary> 
    /// UserFriendly Name 
    /// </summary> 
    public string MerchantName { get; set; } 

    /// Billing Information 
    /// </summary> 
    public virtual ICollection<BillingTransactions> BillingTransactions { get; set; } 

    /// <summary> 
    /// List of Accounts for this merchant (pulled from DBAccounts) 
    /// </summary> 
    public virtual ICollection<UserAccount> UserAccounts { get; set; } 
} 

(兒童或多次)

public class UserAccount 
{ 

    private string loginID; 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    /// <summary> 
    /// Standard ID 
    /// </summary> 
    public int ID { get; set; } 

    public int MerchantId { get; set; } 

    [ForeignKey("ID")]  
    public Merchant Merchant { get; set; } 
    //Obviously there are more properties here.... 
} 

我創建如下新實體:

public void CreateNewMerchant(UserAccount useraccount) 
    { 
     Merchant merchant; 
     if (useraccount.Merchant == null) //New unknown merchant 
     { 
      merchant = new Model.Merchant.Merchant(); 
      merchant.UserAccounts = new List<UserAccount>(); 
      merchant.UserAccounts.Add(useraccount); 
     } 
     else 
     { 
      merchant = useraccount.Merchant; 
     } 

     ServiceBase<Merchant> sb = new Core.ServiceBase<Merchant>(); 
     base.Add(merchant); 
     base.Save(); 




    } 

這是爲像表單界面的嚮導。第一步是創建一個用戶帳戶。下一步是填寫新的商家信息。嚮導步驟正在創建子對象useraccount和一個空父對象,然後在下一步創建父對象。

我的代碼正在創建一個空白/空的父項,並將子項/ useraccount添加到空商家並添加到數據庫中。

爲什麼我得到無效的轉換異常?

回答

1

你需要......

[ForeignKey("MerchantId")] 
public Merchant Merchant { get; set; } 

...而不是[ForeignKey("ID")]將使用主鍵爲外鍵,從而定義了一個對一個,而不是一個一對多的關係。

+0

謝謝你的工作。我可能會嘗試將我自己的小技巧和提示放在一起。標準教程非常容易混淆外鍵名稱和正確的方法。 – DanScan