C# 转换错误int?在实体框架中字符串
在PK和FK具有不同类型的表中尝试左联接时遇到问题。 智力?转换为字符串,十进制转换为字符串,反之亦然C# 转换错误int?在实体框架中字符串,c#,asp.net-mvc,entity-framework,linq,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() { p
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服务器甚至不允许您建立这种类型的关系。如果您不介意使用一点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();
类似查询,并访问以下值:
var query = (from t1 in context.VDB_TABLE1);
query.Id
query.AnotherValue
query.Table2.AnotherValue
query.Table3.AnotherValue
警告,这是非常低效的。您正在对主表中的每条记录进行两个额外的db调用。如果您只有几条记录……那么这对您来说可能没问题。您是如何创建指向不同数据类型的外键的?还是“假”外键?如果是后者,你需要自己处理转换。正如@Albireo所说,FK应该共享它引用的PK的数据类型,否则它们不是合适的FK。最好重新设计DB表以符合正确的practice@Albireo这就是问题所在,我无法修改数据库结构,因为数据库客户端正在运行,并且在该结构中已经有系统,只是不知道它们是如何工作的'rs@Takarii这就是问题所在,我无法修改数据库结构,因为数据库客户端正在运行,并且此结构中已经有系统,只是不知道它们是如何工作的。在这种情况下,获取两个值,将它们解析为字符串,并使用c#进行比较。根据结果,做“事”
var query = (from t1 in context.VDB_TABLE1);
query.Id
query.AnotherValue
query.Table2.AnotherValue
query.Table3.AnotherValue