How can i extend a class that represents a table in a database with a few in-memory properties?

I have to do a lot of repetitive work on a database that's readonly to me.
I hoped to be able to extend a class that is automatically available when i make the connection to the database.
But i'm not sure how to do so.
I have to extend the class with a few in-memory properties to be able to record some specifics.
Any thoughts on how to do so? Or suggestions for google searches?


  • The entity classes generated by linqpad are just regular classes that are unsealed and can be extended from. You could either define a class that directly then project to the class or just use an anonymous class to copy all the fields over and add properties as needed.

    Using the anonymous type is the quickest way. Assuming you have a license, when adding properties to the object, choose the "all properties and fields" option to map all values.

    You could then add any additional properties you need. The underlying database data and schema will remain untouched.

  • There are probably several ways of doing this and it depends on how much work you want to do upfront.

    It is quite a bit of work, but if the schema is unlikely to change, you could create your own typed data context containing your extra properties.

    With LinqPad 5 you can base this on Linq2Sql or EntityFramework, but If you are using LinqPad 7 you might be better using EF as it doesn't by default support a custom Linq2Sql assembly. (I think there is a third party driver, but have not used it).

    To get started with your context, you can use an existing LinqPad connection and then decompile the generated dll into a project for amending.

    GetType().BaseType.Assembly.Location.Dump(); will show you the location of the dll.

    A much simpler method would be to define a new wrapped class like below (this is based on the NorthWind database)

    void Main()
        var query= Customers.Take(5).Dump();
        var list = query.Select(a=>new ExtendedCustomers(a)).ToList();
        list.First().MyExtraString = "Test";
        list[1].MyExtraInt = 1;
    public class ExtendedCustomers
        public Customers BaseObject;
        public string MyExtraString;  
        public int MyExtraInt ;  
        public ExtendedCustomers(Customers c)
            BaseObject = c;
        object ToDump() => Util.Merge(BaseObject, new { MyExtraString, MyExtraInt});

    This is using the new Util.Merge feature of Linqpad 7 (perhaps beta), to make things easier, but that is not a requirement.


    The downside is that when dumping just some of the ExtendedCustomers fields, it is not quite as simple as before

    i.e. instead of doing

    (from r in list select new { r.CustomerID, r.CompanyName , r.MyExtraString}).Dump();

    you need to reference the BaseObject , ie

    (from r in list select new { r.BaseObject.CustomerID, r.BaseObject.CompanyName , r.MyExtraString}).Dump();
Sign In or Register to comment.