[英]Conversion error int? to string in Entity Framework
I have problems trying to left join in a table where the PK and FK has different types. 我在尝试在PK和FK具有不同类型的表中保留联接时遇到问题。 int? 诠释? to string, decimal to string and vice-versa 到字符串,十进制到字符串,反之亦然
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;}
}
That's my ViewModel: 那就是我的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;}
}
The query: 查询:
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();
It may be impossible to get EF to behave this way. EF可能无法以这种方式运行。 MSSQL Server will not even let you make this type of relationship. MSSQL Server甚至不允许您建立这种类型的关系。 If you don't mind a little SQL, you can do what you want using LinqToSQL 如果您不介意使用SQL,可以使用LinqToSQL做您想做的事
Modify your view model 修改您的视图模型
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();
One other option would be to change your model like so. 另一种选择是像这样更改您的模型。
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
}
Query like so, and access the values like: 像这样查询,并访问类似的值:
var query = (from t1 in context.VDB_TABLE1);
query.Id
query.AnotherValue
query.Table2.AnotherValue
query.Table3.AnotherValue
Warning, this is very inefficient. 警告,这是非常低效的。 You are making two extra db calls for every record in your primary table. 您正在对主表中的每个记录进行两个额外的数据库调用。 If you only have a few records...then this might be OK for you. 如果您只有几条记录...那么这对您来说可能就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.