I am learning Entity Framework to query the database of my company. I have an ASP.NET MVC project and as of now, I have established a connection to the company's principal server database. That has given me access to all the tables and I created a separate class Library containing all the corresponding POCOs(generated automatically).
In the tutorial I was following they say to use "enable-migrations" to have the database updated with the model.
So does that mean that if I were to modify the models in my project, that would have a direct effect on the database? Since I am new to this project I do not want to do anything stupid, like altering the database. For now I just want to query the database and retrieve information, then use that information to show more or less information on a web page.
EDIT: Just as an example, I would like to show a difference between the model generated by EF and what my real table looks like. I have a table Web_Profils that contain and ID, a ProfileName and an Order (int). This DB has no primary keys or foreign keys. If there are relations, they are defined through new tables. But when EF generates all my classes, it adds ICollections, for example in Web_Profils, I have a.o virtual ICollection<Web_User_joint_Profils>Web_User_joint_Profils which is not present in the actual table, it just seems to be the relation that EF has deduced(it is the relation between Users and Profiles present in the table Web_User_joint_Profils). Now, will doing a migration affect my tables just because EF has added these collections in my model?
I've also read that it is possible to deactivate migrations using :
Database.SetInitializer(new ContextInitializerNone<YourDbContext>());
Any thoughts?
If you update your model, you need to add a migration to your project and update your database with that migration.
Unless you do those steps after updating your model, changes will not be reflected in the database.
Related
I receive a large JSON having different recordsets in the form of arrays in a Xamarin-Forms application. The recordsets are linked with each other through reference Ids. Basically the data is coming from a relational database and I have to map the data into the device's local SQLite. I am using EFCore for that. I am able to successfully set up the Models and their FKs using OnModelCreating override. I have verified it by logging the table creation scripts. Now the issue is, when I AddRange a list of some records, EF Core automatically deletes some of the records. I don't know why and how.
Here is the screenshot in debugging:
The data is a huge graph of different relational records. Earlier I was trying to Add the whole graph by saving only the grandparent record. But there are several children who reference the same record more than once. For example, a UserType is referenced by many users. So EF throws Identity tracking issues. Then I decided to not save using the graph, instead save table by table. And now I am facing this issue. To be specific, there is a total of 11 tables involved in my saving. I am able to save 5 tables that have independent data e.g. UserTypes, EntityTypes, ContactTypes, etc. When I came to the 6th table which references some records of 5 saved tables, I am getting this issue.
Update:
I solved the problem. The issue was in a relationship that was wrongly defined. A WorkOrder can have one Customer only, but a Customer can be linked to many WorkOrders. I was taking it as One-to-One but was ignoring the other way. I updated the one-to-one to one-to-many in Customer entity and everything started working great!
By the way, this we can say the beauty and perfection of EF Core that it can never allow you to persist data against the rules you have defined. Though automatic deleting was a little confusing but ultimately that was my mistake.
I am new to Entity Framework. I have created an EF Model and successfully added some tables and relation. Then I Clicked Generate Database from Model and My DB has been updated. Then I renamed some columns and I don't know how to revert or apply the changes. And Update Model from database does not seems to work because the columns names are different yet.
I need to graphically sync DB with Model. I prefer the model data rather than db data.
Thanks in advance.
You might want to look into the Code-First approach of Entity Framework. Using that approach you'll define your model in your code, and when changing anything you can create a Migration which allows you to up- and down-grade the DB to a specific version from the package manager console (or just create the respective SQL scripts).
For more information on this subject please see this article on MSDN
Note that you can also reverse engineer the code first model from an existing database (see 3. Reverse Engineer Model in this MSDN article), and then enable migrations for that model (see Step 2: Enable Migrations in this MSDN article)
What I do when I make "updates" is do it on both sides manually, in db and then in model (by right click properties) if the change is small. If adding a "new" table I drag it over to model from db server connections panel.
The alternative I've seen others prefer to use in this cases is to stay away from Entity Framework and use Dapper where you pass queries to it and it handles the rest.
Dapper (Wins!) vs Entity Framework vs ADO.NET Performance Benchmarking
I have an odd situation. I am working on a project with a very large existing database that is completely unrelated, but does contain corresponding table id's. It's as if someone copied the database but never related the tables.
In Entity Framework, is there a way to go EF code first and create the relationships in code, but Not apply those relationships in the database? I would like to go through and relate the database but the client doesn't want to pay to fix it.
Thanks!
In this instance, it seems you would be best to add relationships directly to your database (or to a duplicated database for testing/staging) and then just update your entities using your test connection and regression test your app.
Assumptions
Using EF 6.1, MVC 5, VS 2013, C#
I have an existing database model designed in Toad DM for SQL Server and it's very important keep it always updated
Steps and Notes
Using ADO.NET Entity Data Model I chose Code First from Database (new feature in EF 6.1) to generate the models. Note: Model classes and DbContext class generated successfuly but NO .edmx or .tt file was generated.
Next I added a new scaffold item: MVC 5 Controllers with views, using Entity Framework. Note: Success, controllers and views generated
Question
From now on I don't want to use Code First to update my database. Instead I want the models to be updated based on database changes. What to do next? If I don't have an edmx file will I not be able to update my model classes from the database?
The Entity Data Model Wizard's Code First from Database does an excellent job creating your entity classes, as if they were created in the Code First style. What you are asking is if there is any way to keep these classes up-to-date as your database changes, similar to the EDMX style "Update Model From Database". From what I've researched this is not possible using the built-in tooling. However, here is one workaround that I've found useful:
Let's say I have database with a product table and customer table. Originally I created a StoreDBContext class, and selected product as one of my objects. Now I want to add the customer table as a new entity to the existing context. Here's how to do this using the Code First Wizard:
Create a new Entity Data Model, call it StoreDBContextTemp or whatever
Choose the code first from database wizard option
Select customer as an object to add (just customer) & complete the wizard
Open the newly created context file, StoreDBContextTemp.cs, and copy the virtual properties of your newly added entities:
public virtual DbSet<Customer> Customers {get; set;}
Paste these new properties into your Original StoreDBContext.cs dbcontext class.
Delete StoreDBContextTemp.cs, and remove the connection string for StoreDBContextTemp in app.config/web.confg etc.
You can now use Customer on the StoreDBContext class
If you add or remove tables you will need to manually adjust fields, but at least you won't need to hand write dozens of properties each time a new table is added to the model.
One more option is just delete the auto generated classes from the project and once again generate them.
While following this approach only thing we need to make sure that is we should give the same name for the data model(class name which inherits from DbContext ) as the previous one.Data model name is highlighted in below snap
Three things.
There's no .edmx when you use Code First.
If you use Code First Migrations you would have to write first the code and after that migrate the changes to database. This helps you to have much more organized you code with no generated code which is an advantage.
There's a plugin in Visual Studio for doing contrary. Entity Framework PowerTools allows you to select the database and map it to objects.
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
The best solution to me is deleting the model and recreate updated one with the same name, keeping in mind two points:
Personal extension methods implemented for the model;
Possible manual relationships between tables added to the model because of not setted up in the phisical db.
My personal solution:
Move all extension methods to another partial class that won't be overrided;
Insert all added properties of an entity to another partial class;
Keep track of all manual relationships in an help file, so you can add them again being sure not to loose anything;
Delete the old model and recreate one new with the same name and update it with the manual relationships of point 3.
Is it possible to add fields to an entity framework class that rather than being mapped to a column in a table instead map to a SQL query?
For a contrived example (NB: This is not what I'm actually trying to do just an easier to explain example of what I'm trying to accomplish) I want my class to have a TableCount field that holds the result of SELECT COUNT(*) FROM MyTable at the time the object was loaded from the db.
EDIT: I should have mentioned this in my original post but I'm using POCO classes.
You cannot do it directly with entity mapped to a database but there are two ways how to achieve it with a new entity type containing columns from your original entity and your additional computed columns:
Create database view and map that view - this is fully automatic way maintained by EDMX designer for you
Write query to populate whole new entity type and map it manually in DefiningQuery. The disadvantage is that it requires manual EDMX editing and without additional (commercial) tool also manual maintenance of EDMX because standard VS EDMX Designer overwrites edited SSDL part every time you select update from database.