DataContext-通过LINQ查询时自动加载可选引用值
我有以下情况(例如) 我有一个名为Master.dbml的DataContext 它有两个表:DataContext-通过LINQ查询时自动加载可选引用值,linq,linq-to-sql,datacontext,Linq,Linq To Sql,Datacontext,我有以下情况(例如) 我有一个名为Master.dbml的DataContext 它有两个表: 爱好{id;name;} HobbyReference{id;Hobby\u Name;Hobby\u Good\u Name;} 当我查询Hobby时,DataContext应该检查(伪代码): 这方面的最佳实践是什么 我知道如何做(扩展datacontext),但不知道如何完全实现它 我该怎么做?业余爱好。业余爱好的名称不存在 无论如何,要在从datacontext返回之前进行检查,您可以执行
- 爱好{id;name;}
- HobbyReference{id;Hobby\u Name;Hobby\u Good\u Name;}
我该怎么做?
业余爱好。业余爱好的名称不存在
无论如何,要在从datacontext返回之前进行检查,您可以执行以下操作:
public class HobbyDataService
{
MasterDataContext db = null;
public HobbyDataService(string connection)
{
db = new MasterDataContext(connection);
}
internal string GetHoppyName(string hobbyName)
{
var x = from hr in this.db.HobbyReferences
where string.Equals(hr.Hoppy_Name, hobbyName)
select hr;
if (x.Any())
return x.First().Hobby_Good_Name;
else
{
//Return what ever you want here
}
}
}
public partial class Hobby
{
public static string GetName(string hobbyName, string connection)
{
if (String.IsNullOrEmpty(hobbyName))
throw new ArgumentException("hobbyName is null or empty.", "hobbyName");
if (String.IsNullOrEmpty(connection))
throw new ArgumentException("connection is null or empty.", "connection");
HobbyDataService dataSrvce = new HobbyDataService(connection);
return dataSrvce.GetHoppyName(hobbyName);
}
}
如果每个名字在HobbyReference上的条目不超过一个,并且用于查询(即不用于更新),那么您可以执行以下操作
public class AmendedHobby
{
public int Id { get; set ;}
public string Name{ get; set ;}
}
public IQueryable<AmendedHobby> GetAmendedHobbies()
{
return
(from h in Hobby
join hr in HobbyRefernce on h.Name equals hr.Name into hrResults
from hr in hrResults.DefaultIfEmpty()
select new { h.id , Name = hr.Hobby_Good.Name ?? r.Name}
}
它将返回AmendDedHobby类,因为它没有链接到现有表,这意味着更改不会持久化回数据库
public class AmendedHobby
{
public int Id { get; set ;}
public string Name{ get; set ;}
}
public IQueryable<AmendedHobby> GetAmendedHobbies()
{
return
(from h in Hobby
join hr in HobbyRefernce on h.Name equals hr.Name into hrResults
from hr in hrResults.DefaultIfEmpty()
select new { h.id , Name = hr.Hobby_Good.Name ?? r.Name}
}
(from r in GetAmendedHobbies() where r.Name == "Football" select r)