How to get an Entity Framework class inherit a base class
I have several classes that inherit from an abstract base class that holds some common utility code. I want to move to EF for data access but I'd still like the objects to inher开发者_如何学JAVAit the common code in the base class. The EF classes already inherit from EntityObject so I can't have them inherit my base class. What's the right way to handle this? My environment is Net 3.5/C#
Sorry if you saw my earlier post -- I missed something important in your question.
You can use partial classes. Make your partial class have an internal field with an instance of the base class you want and implement all the methods and properties (unless they are already implemented in the entity). If you are trying, then, to allow use of your entity class, you can use a public static implicit operator
in your base class (or in the partial entity class) to allow the conversion without hassle.
If you have an abstract base class called MyBaseClass, you can do something like:
public partial class MyEntityClass
{
private MyBaseClass _baseClass;
private MyBaseClass BaseClass
{
get
{
if (_baseClass == null)
{
_baseClass = new MyBaseClass();
}
return _baseClass;
}
}
public string BaseClassString
{
get
{
return BaseClass.BaseClassString;
}
set
{
BaseClass.BaseClassString = value;
}
}
// etc.
public static implicit operator MyBaseClass(MyEntityClass e)
{
return new MyBaseClass() {
Property1 = e.Property1,
Property2 = e.Property2 // etc.
};
}
public static implicit operator MyEntityClass(MyBaseClass b)
{
return new MyEntityClass() {
Property1 = b.Property1,
Property2 = b.Property2 // etc.
};
}
}
If you're still using Visual Studio 2008, I'm not sure you're going to be able to accomplish this (although someone please feel free to correct me).
But if you're using VS2010 then you can use the new T4 templating options (even while targeting .net 3.5). What I would do is make your base class inherit from the EntityObject class, and then modify the t4 templates used to generate the classes to inherit from your base class.
If you're still in VS2008, you can probably still do the same thing, you'll just have to modify the generated CS files by hand (every time you change your model), which granted is going to be horrible.
精彩评论