How should I modify database model in Entity Framework? - sql

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.

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:
Create another partial class to the generated classes
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.
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:
Make changes to your model in the EDMX designer
Right-click on the EDMX design surface -> Generate Database from Model.
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.

Related

ASP.NET MVC is it okay to work with the ApplicationUser model for account management?

I know that each time a user registers in my ASP.NET MVC application the ApplicationUser class is used to create the new record and put it in the database.
I was wondering if it's okay to add properties to that class for example I want the model to have a column in the database for DateOfBirth. Then use that class(model) directly in my application when I have to do some business logic things, database queries and similar stuff. Or is it more correct to create a new table in the database called let's say ApplicationAccounts, that saves the general info about the account. Each ApplicationAccount will be associated with a ApplicationUser(1 to 1 relation) and be somewhat of a buffer in the communication with the real accounts. Does that make sense?
I would go with the second option : create your own table, link them up in a one to one relationship using the UserID as a unique foreign key and then go from there.
One note here, it is perfectly normal for the model you need for the views to be different from the database model, this is because your db model can hold a lot of data that your view doesn't actually need. You might want to consider having separate models and use something like Automapper for a quick translation from one to another.

Is it possible to alter database using EntityFramework- Database First workflow

is it possible to change database tables (e.g adding a field in a particular table) in an application using Entity framework.??
My application used an existing database to generate a model nd entity classes out of that database, if now I want to change tables in my existing database , how can I do that using Entity framework, so that:
Changes are saved in previously generated Entity classes
Changes are saved in database also.
Well you'll either have to change the database or the model classes.. If you don't want to update both manually, you could just update the database DDL and then generate the Entity model again.

MVC4 SimpleMembership Connection Strings

Ihave a DB First EF5 project that I am implementing SimpleMembership in. I have most of it working, but a question has come up.
The main User table created by Simple Membership has the UserName in it. I have a couple other places in the app where I need to query this table, specifically the userName. Simple Membership does not use the Data.EntityClient in the connection string, so i have it set to the SqlClient.
So because i don't have an entity model with the provider User table, I am not sure how to query it. Usually i would create an instance of the entity model and use LINQ on it, but when I try it I get a very long winded error about mixing code first with entity first. I have modified the 'initialSimpleMembershipAttribute' so it points to the separate connection string I made for the Membership tables.
One solution i thought of was to save the user, then copy the username to one of my custom tables, then i can query it through EF, but this seems like it would violate some kind database 'best practice' of duplicated data.
Another idea I had is to create a second edmx model for the tables that Membership created, but if SimpleMembership does not use the EntityClient, does that also mean it will not recognize a entity model?
You're way over complicating things.
If you have your own model, then you can just get rid of the model that the default template gives you, and use yours instead. It doesn't matter if it's Code first or database first or whatever. Just change the Initialize SimpleMembershipAttribute to remove the references to the default model they give you, and make sure you modify the InitializeDatabaseConnection call correctly.
WebSecurity.InitializeDatabaseConnection("YourConnection", "WhateverYouCallYourUserTable",
"WhateverYourUserIdIs", "WhateverYourUserNameColumnIs", autoCreateTables: true);

Sql Azure CompatibleWithModel not working

In my code I am trying to check if my entity framework Code First model and Sql Azure database are in sync by using the "mycontext.Database.CompatibleWithModel(true)". However when there is an incompatibility this line falls over with the following exception.
"The model backing the 'MyContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."
This seems to defeat the purpose of the check as the very check itself is falling over as a result of the incompatibility.
For various reasons I don't want to use the Database.SetInitializer approach.
Any suggestions?
Is this a particular Sql Azure problem?
Thanks
Martin
Please check out the ScottGu blog below:
http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx
Here is what is going on and what to do about it:
When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We'll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:
Database.SetInitializer<Production>(null);
Using above code you are no recreating the database instead using the existing one so I don't think using Database.SetInitializer is a concern unless you have some serious thoughts about using it.
More info: Entity Framework Code Only error: the model backing the context has changed since the database was created

SQL views with Entity Framework

I have a SQL view to integrate with my application. I have been using Entity Framework till now. But the problem is that when I add a view to Entity Framework it starts treating my view as a table.
What I really want to know is, am I missing on something? Also if I use Nhibernate will this problem be resolved? Will it treat the view as a view only?
This view is a very complex query which has multiple joins and aggregation. That is why I am using a view.
But the problem is that when I add a view to Entity Framework it
starts treating my view as a table.
No it doesn't. If you add view to your model through wizard (EDMX designer) it will internally handle the view as a defining query which makes readonly entity. At entity level (the conceptual model) you don't see a difference because it is just another entity / class but if you try to make changes to instance of that class and save them you will get an exception (unless you map stored procedures or custom SQL commands to insert, update and delete operations for that entity).
Edit:
Database views as well as other database specific features like stored procedures or SQL functions are only for database first scenario (when you are using Update model from database in the designer).
Using Generate database from model is for Model first scenario where you tell VS: "Here is my model and I want some database to store it." First of all only information from conceptual model is used (original mapping and database description is replaced with a new one every time you run this command so even mapping to original database can be broken). It cannot create database specific features for you because it doesn't know that class should be mapped to view and moreover it doesn't know how should the view be created (the query from original view is unknown).
You can force VS to create the view for you but it is a lot of work in T4 templates where you will have to somehow provide SQL creation script for the view.