代码之家  ›  专栏  ›  技术社区  ›  Jedidja

如何为相同的LINQ 2 SQL表创建外观?

  •  1
  • Jedidja  · 技术社区  · 17 年前

    我想创建一种访问特定表的通用方法,但似乎无法使其正常工作。

     public interface ILetter
     {
         DateTime CreationDate { get; }
     }
    
     public interface IBill
     {
         DateTime BillDate { get; }
     }
    
     // The LINQ 2 SQL generated classes already implement the CreationDate property
     public partial class NewLetter : ILetter { }
     public partial class CurrentLetter : ILetter { }
     public partial class HistoricLetter : ILetter { }
    

    然后在我的代码中,我希望能够做到这一点:

     switch (type)
     {
       case 1:
         Table<IBill> specificBill;
         switch (location)      
         {
            ...
         }
    
       case 2:
         Table<ILetter> specificTable;
         switch (location)
         {
           case 1: specificTable = dataContext.NewLetter as Table<ILetter>; break;
           case 2: specificTable = dataContext.CurrentLetter ...
           case 3: specificTable = dataContext.HistoricLetter ...
          }   
     }
    

    或者类似的东西。不幸的是我不能投 Table<NewLetter> 到 Table<ILetter>

    2 回复  |  直到 17 年前
        1
  •  1
  •   Thomas Eyde    16 年前

    这个 DataContext 具有检索所需表的通用方法:

    var table = dataContext.GetTable<NewLetter>();
    

    也许你可以用它来重写你的查询:

    var table = dataContext.GetTable<NewLetter>();
    var letters = 
        from letter in table
        where ...
        select letter as ILetter;
    
        2
  •  0
  •   leppie    17 年前

    看看Linq2SQL中的继承。您的表将需要某种类型的鉴别器列/属性。