【问题标题】:DataContext - Load optional Referenced values automaticly when querying through LINQDataContext - 通过 LINQ 查询时自动加载可选的引用值
【发布时间】:2011-04-21 09:43:05
【问题描述】:

我有以下情况(例如)

我有一个名为: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

这方面的最佳做法是什么?

我有一个想法(扩展数据上下文),但我不知道如何完全实现它。

我该怎么做?

【问题讨论】:

    标签: linq linq-to-sql datacontext


    【解决方案1】:

    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);
            }
        }
    

    【讨论】:

      【解决方案2】:

      如果 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 类,因为它没有链接到现有表,这意味着更改不会被持久化回数据库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        • 2010-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多