2015-12-08 107 views
3

嘗試保存更改時收到以下異常:System.Data.SqlClient.SqlException:無效的列名'ClientID'。 列名'ID'無效。實體框架忽略NotMapped屬性

ClientID屬性具有[NotMapped]屬性,並且該類沒有ID屬性。另外,數據庫表匹配正確的屬性。我知道有時EntityFramework會在你有一個沒有關聯FK的導航屬性時創建隱式外鍵列,但在這裏並不是這樣。

public class AccountPreference : fgleo.Objects.PortfolioManagement.IAccountPreference 
{ 
    #region Constructors 

    public AccountPreference() { } 

    #endregion 

    #region Fields & Properties 

    public Guid Guid { set; get; } 

    [ForeignKey("Account"), Key] 
    public int AccountID { set; get; } 
    public virtual tAccount Account 
    { 
     get; 
     set; 
    } 

    public string Nickname { set; get; } 


    public string AccountType { set; get; } 


    public string InsuranceCompanyName { set; get; } 


    public string PolicyName { set; get; } 


    public ContainerType ContainerType { set; get; } 


    public bool Hide { set; get; } 


    public bool IsActive { set; get; } 


    public bool IsReviewed { set; get; } 


    public bool IsPreserved { set; get; } 


    public bool IsImplemented { set; get; } 


    public bool AllocateByAccount { set; get; } 


    public bool IsActivelyManaged { set; get; } 


    public int AccountRiskTolerance { set; get; } 

    public decimal? BalanceAtAccountLock { set; get; } 


    public bool AddCashHolding { set; get; } 


    public bool RefreshCalcs { set; get; } 


    public bool UsePortfolioOverride { set; get; } 


    public bool UseBestOfClassOverride { set; get; } 


    public bool UseSavedRecommendations { set; get; } 


    public bool WaitingForTimer { set; get; } 


    public AccountPendingStatus PendingStatus { set; get; } 


    public DateTime? DatePendingChange { set; get; } 

    [NotMapped] 
    public int ClientID 
    { 
     get 
     { 
      return (int) ClientIDNullable; 
     } 
     set 
     { 
      this.ClientIDNullable = value; 
     } 
    } 

    public virtual Client Client { get; set; } 
    [ForeignKey("Client")] 
    public int? ClientIDNullable { get; set; } 


    #endregion 


} 

最奇怪的是,這個代碼工作完全正常在本地,而不是在我們的生產環境。我檢查過數據庫,它看起來是相同的。

+0

您可以發佈產生此錯誤的實體的類定義嗎?我有一個理論,但沒有完整的定義,很難說它是否是遠程正確的。 –

+0

我在課堂上編輯過。 –

+1

'Client'實際上是否包含一個名爲'ClientIDNullable'的字段?如果您不告訴它,則EF約定會爲主鍵字段查找「 Id」或「Id」。它可能會試圖根據您的導航屬性進行關聯,並且事情可能會變得很奇怪。 –

回答

2

實際的錯誤來自存儲過程。這非常令人困惑,因爲實體框架沒有轉儲整個錯誤消息(包括過程的名稱),並且看起來像EF只是生成不正確的SQL。相反,存儲過程只是有一些過時的定義,導致該問題。

4

沒有更多的信息或代碼示例,如果您使用Fluent API,則不知道。

用流利的API的情況下,你也可以使用OnModelCreating事件,忽略性能,如下:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<YourModel>().Ignore(t => t.ClientID); 
    base.OnModelCreating(modelBuilder); 
} 

Here是一些有用的信息。

+0

這可能適用於ClientID屬性,但甚至沒有要忽略的ID屬性(即,如果以這種方式執行操作,我將嘗試忽略不存在的屬性而導致編譯時錯誤)。 –