Mike
Mike

Reputation: 151

How should I modify database model in Entity Framework?

EF beginner here.

How am I supposed to make changes in database model using Entity Framework?

I mean in DB model like changing datatypes of columns, adding attributes etc.?

E.g. I have string Password property in User table and I want to add [DataType(DataType.Password)] Attribute or [Required] or anything.

How am I supposed to do that? Of course along with applying changes to my DB? I created DB model from mdf local file (detached from mssql studio) using 'EF Designer from database' so I have my emdx model inside Models (asp.net mvc5) with classes for each table and DB MDF in App_Data.

Am I suppose to modify these classes?

Because I can add attributes right there but Diagram doesn't change and DB doesn't change. I guess I have to commit changes somehow.

I'll add that I can't enable migrations: Creating a DbModelBuilder or writing the EDMX from a DbContext created using Database First or Model First is not supported.

EDMX can only be obtained from a Code First DbContext created without using an existing DbCompiledModel.

Upvotes: 0

Views: 1958

Answers (1)

Tsahi Asher
Tsahi Asher

Reputation: 1810

I think you are mixing allot of things here.

If you have an EDMX file, then your models are generated at compile time (or you can generate them from right click on the Model.tt file -> Run Custom Tool). So adding attributes to properties in a class representing a model entity will indeed be overwritten the next time you compile. The solution is:

  1. Create another partial class to the generated classes
  2. In the partial class, decorate the class with the [MetadataType] attribute and give it a type of a metadata class. The metadata class is a simple class, with the same properties as the generated class, but a different name, to prevent naming conflicts. From a design point of view, it should be abstract, because you're not supposed to create instances of it, but this is not required.
  3. In the metadata class, decorate the matching properties with the validation and DataType attributes.

To the best of my knowledge, using model-first or database-first doesn't support migrations as in code-first. If you want to make changes to your schema (semi) automatically, I believe your best option is:

  1. Make changes to your model in the EDMX designer
  2. Right-click on the EDMX design surface -> Generate Database from Model.
  3. After selecting the connection to your database, this will generate the SQL to generate your schema. This is a bit clunky, because it will erase your data each time, so you should have a script in place to re-populate your database after each time.

Upvotes: 2

Related Questions