繁体   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