Entity Framework Database first How to alter entit

2019-06-20 17:25发布

I have a database already full of tables with data in them. What I have seen is that all tables have 5 columns in common:

  • Id-long, key
  • IsDeleted, bit
  • DateDeleted, SmallDatetime
  • LastUpdated, SmallDatetime
  • LastUpdatedUser, nvarchar

Now, there are some common operations that are done based on those fields which currently are replicated everywhere

What I want is to create a base class containing just these common attributes and the methods done to them and make every other entity derive from this.

I don't need or want to have this base entity on the database per se, this is just something I want to help the coding part.

The issue is this is Database first, I cannot alter the database so all I have to work with are the POCO classes and the EDMX.

How can i achieve this?

2条回答
Root(大扎)
2楼-- · 2019-06-20 18:02

What you are looking for is something similar to TPH (http://msdn.microsoft.com/en-us/data/jj618292.aspx)

I don't think this will work for you however, as you have multiple existing tables.

One of the possible solutions is:

  1. Create a base class called "BaseModel" (or something like that)
  2. Add those properties as abstracts to force them to be overridden
  3. Create a method in that base class to populate those fields, or create a helper which takes BaseModel, IsDeleted,LastUpdated, LastUpdatedUser as a parameter and update the model.
  4. Extend the partial classes generated by the model.tt file and inherit from the BaseModel class.

Thanks, Dave

查看更多
淡お忘
3楼-- · 2019-06-20 18:04
  1. Expand the .edmx file and open the Model.tt file (not the Model.Context.tt one)
  2. Find the row where the definition of the "partial class" is being announced.
  3. Should look something like that: <#=codeStringGenerator.EntityClassOpening(entity)#>
  4. Add the inheritance " : YourBaseClass" to the end of the row

Done. Once you save the model you will have all your old entities deriving the base class and when a new one is generated by this template it will derive the base class as well.

查看更多
登录 后发表回答