2011-04-21 55 views
0

查询时全自动加载可选参考值I有以下的情况(如实施例)的DataContext - 通过LINQ

我有一个名为的DataContext:Master.dbml

它有2个表:

  • 业余爱好{ID,名称;}
  • HobbyReference {ID; Hobby_Name; Hobby_Good_Name;}

总是当我查询业余爱好,在DataContext应该检查一下(伪代码):

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

什么是最好的做法角落找寻呢?

我有一个想法如何做到这一点(扩展datacontext),但我不知道如何完全实现它。

我该怎么做?

回答

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); 
     } 
    } 
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类,该类由于没有链接到现有表,意味着更改不会被持久化回数据库。