I have problems trying to left join in a table where the PK and FK has different types. 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:
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. MSSQL Server will not even let you make this type of relationship. If you don't mind a little SQL, you can do what you want using 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.