簡體   English   中英

轉換錯誤為int? 在實體框架中字符串

[英]Conversion error int? to string in Entity Framework

我在嘗試在PK和FK具有不同類型的表中保留聯接時遇到問題。 詮釋? 到字符串,十進制到字符串,反之亦然

public VDB_TABLE1()
{
   public int Id {get; set;}
   public string AnotherValue {get; set;}
   public string FKTable2 {get; set;}
   public string FKTable3 {get; set;}
}

public VDB_TABLE2()
{
   public int? PKTable2 {get; set;}
   public string AnotherValue {get; set;}
}

public VDB_TABLE3()
{
   public decimal PKTable3 {get; set;}
   public string AnotherValue {get; set;}
}

那就是我的ViewModel:

public VDB_MYVIEWMODEL()
{
   public int Id {get; set;}
   public string AnotherValue {get; set;}
   public VDB_TABLE2 TABLE2 {get; set;}
   public VDB_TABLE3 TABLE3 {get; set;}
}

查詢:

 var query = (from t1 in context.VDB_TABLE1
                from t2 in context.VDB_TABLE2.Where(t2 => t2.PKTable2 == t1.FKTable2).DefaultIfEmpty()
                from t3 in context.VDB_TABLE3.Where(t3 => t3.PKTable3 == t1.FKTable3).DefaultIfEmpty()
 select new MYVIEWMODEL
 {
   Id = t1.Id,
   AnotherValue = t1.AnotherValue,
   TABLE2 = t2,
   TABLE3 = t3
 }).ToList();

EF可能無法以這種方式運行。 MSSQL Server甚至不允許您建立這種類型的關系。 如果您不介意使用SQL,可以使用LinqToSQL做您想做的事

修改您的視圖模型

public VDB_MYVIEWMODEL()
{
   public int Id {get; set;}
   public string AnotherValue {get; set;}
   public string T2 {get; set;}
   public string T3 {get; set;}
}

string sSQL "Select VDB_TABLE1.Id, VDB_TABLE1.AnotherValue, VDB_TABLE2.AnotherValue as T2, VDB_TABLE3.AnotherValue as T3 from VDB_TABLE1 left join VDB_TABLE2 on VDB_TABLE1.FKTable2 = VDB_TABLE2.PKTable2 left join VDB_TABLE3 on VDB_TABLE1.FKTable3 = VDB_TABLE3.PKTable3;";

List<VDB_MYVIEWMODEL> Results = context.Database.SqlQuery<VDB_MYVIEWMODEL>(sSql).ToList();

另一種選擇是像這樣更改您的模型。

public VDB_TABLE1()
{
   public int Id {get; set;}
   public string AnotherValue {get; set;}
   public string FKTable2 {get; set;}
   public VDB_TABLE2 Table2
   {
     get
     {
       int id = Convert.ToInt32(FKTable2);
       return context.VDB_TABLE2.Find(id);
     }
   }

   ...do similar for Table3
}

像這樣查詢,並訪問類似的值:

var query = (from t1 in context.VDB_TABLE1);

query.Id
query.AnotherValue
query.Table2.AnotherValue
query.Table3.AnotherValue

警告,這是非常低效的。 您正在對主表中的每個記錄進行兩個額外的數據庫調用。 如果您只有幾條記錄...那么這對您來說可能就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM