tags:

views:

33

answers:

1

Assume I have a table called User. Using LINQ desinger, I will end up with the following:

  • A file called User.dbml
  • A data context class called UserDataContext which subclasses from System.Data.Linq.DataContext
  • A class called User which is mapped from the User table. A UserDataContext object will have a property called Users which is of type System.Data.Linq.Table<User>.

So far so good. Now I want to define a generic base class that converts the Linq.Table property to JSON string for all of its subclasses. So I would have:

using Newtonsoft.Json;

class BasePlugin<T> where T : System.Data.Linq.DataContext, new()
{
    protected T DataContext = new T();
    protected string GetJSONData()
    {            
        //*** DataContext if of type System.Data.Linq.DataContext, therefore it won't know the Linq Table property of its subclasses
        return JsonConvert.SerializeObject(DataContext.Cannot_get_subclass_property_Linq_table);
    }
}

To complete the code in the question, here's an example of a subclass:

class UserPlugin : BasePlugin<UserDataContext>
{
    //The protected member DataContext inherited from BasePlugin 
    //has a property called Users of type System.Data.Linq.Table<User>.
    //The point to to avoid implementing GetJSONData() in all subclasses
}

To summarize, the question is how to avoid implementing GetJSONData() in all subclasses by letting the base class do it.

+1  A: 

It's not clear which table you'd want. There are potentially several tables in a single data context. There may not be in your particular model, but there certainly can be in LINQ to SQL in general.

You can call DataContext.GetTable(Type) or DataContext.GetTable<T> if that's useful... and you could parameterize your class by the entity type as well as the context type:

class BasePlugin<TContext, TEntity> where TContext : DataContext, new()
    where TEntity : class
{
    protected TContext DataContext = new TContext();
    protected string GetJSONData()
    {            
        return JsonConvert.SerializeObject(DataContext.GetTable<TEntity>());
    }
}

Is that what you're after?

Jon Skeet
@Jon Skeet: This is EXACTLY what I'm after. It looks like GetType<TEntity>() causes a compilation error and GetType() would simply be enough, so the second parameterized argument TEntity is not needed?
Khnle
@Khnle: You just need a class constraint on TEntity. Will update the code. You also need to call GetTable, not GetType - typo on my part.
Jon Skeet