DbContext - 通过LINQ查询时自动加载可选的引用值

时间:2011-04-21 09:43:05

标签: linq linq-to-sql datacontext

我有以下情况(例如)

我有一个名为:Master.dbml

的DataContext

它有2个表:

  • 爱好{id; name;}
  • HobbyReference {id; Hobby_Name; Hobby_Good_Name;}

总是当我查询Hobby时,DataContext应该检查是否(伪代码):

 Hobby.Name EXISTS in HobbyReference.Hobby_Name
 THEN 
      take HobbyReference.Hobby_Good_Name
 ELSE 
      take Hobby.Hobby_Name
 END IF

这最好的做法是什么?

我知道如何做(扩展datacontext),但我不知道如何完全实现它。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

Hobby.Hobby_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);
        }
    }

答案 1 :(得分:0)

如果每个名字的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}  
}

这应该允许你做子查询,如

 (from r in GetAmendedHobbies() where r.Name == "Football" select r)

它将返回AmendedHobby类,因为它没有链接到现有表,意味着更改不会持久保存回数据库。