转换错误int?在实体框架

时间:2015-12-17 11:24:05

标签: c# asp.net-mvc entity-framework linq

我在尝试将连接保留在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();

1 个答案:

答案 0 :(得分:0)

可能无法让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

警告,这是非常低效的。您正在为主表中的每个记录进行两次额外的db调用。如果你只有一些记录......那么这对你来说可能没问题。

相关问题