How can I extend a LINQ-to-SQL class without having to make changes every time the code is generated?

删除回忆录丶 提交于 2019-12-05 21:54:38

In response to your comment on the question, the Linq-To-Sql classes are generated as partial. This means you can have separate code files with the same class names declared as partial to add the extra properties you want.

E.g. Your Ling-To-Sql designer class will be:

public partial class Car
{
     .... lots of auto generated stuff ....
}

You can have your own separate file (in the same project) called Car.cs:

public partial class Car
{
     public MyCustomStuff{ get; set; }
}

And the two classes will be merged together. Just make sure they are in the same namespace.

You can create a copy constructor accepting a base class parameter in the derived class:

class MyCar {
    public MyCar(Car car) {
        name = car.name;
        // etc
    }
}

you can't definately cast a Car as MyCar because there is no guarantee that the Car is a MyCar. You can try the cast and see if it works, or you can use the as keyword to try the cast and get null if it fails.

How are the properties set in Car? Why can't MyCar just use the same technique for setting its properties? After all it is a Car. Why do you want to create a MyCar from a Car? Why not just create a MyCar in the first place?

You could also create a constructor in MyCar which takes a Car and assign the properties of MyCar to those of Car in the constructor.

You might also consider using the decorator pattern as an alternative to subclassing, and have your MyCar delegate the calls to the wrapped Car

There are several options you can use:

  • implicit or explicit operator
    public static explicit operator Car(MyCar source)

  • a copy constructor
    public MyCar(Car source)

  • an extension method
    public static class CarExtensions {
    public static MyCar Create(this Car source) }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!