I have been using the Entity Framework, database first design for sometime now which means I've got many references to hundreds of Entity models in code that have been imported based on the name of the database table, of which some are singular and others are plural.
I would like to use the built in function that Entity allows when importing models to automatically make these models singular or plural in code regardless of the database table name however that function only seems to be work when adding NEW models.
QUESTION:
I don't want to have to delete all of my Entity Models and re-import because then my code wouldn't match up to a model without manually changing the many references to those objects. Does anyone know of a way to do this?
If anyone is unsure of what I'm referring to:
Entity Framework does not provide this refactoring functionality.
I ended up removing all models and reading them into my project with the proper naming scheme and then manually refactored all references to the models in code.
Related
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.
I have 20 class.cs with x00s properties for my old project
and now i want to use EntityFramework
but I dont want to rewrite all this classes from begin
i just want to convert this class to DataModel.dbml or use some thing like add Existing Item
and I tried creat class with same name and copy the code inside them but the editor clear them after saving
how can i do that ?
There is plenty of resources regarding Plain Old CLR Objects and Entity Framework code first model on the web.
ADO.NET EF 4.0: Working with Plain Old CLR Objects (POCO) Classes
Code First step by step tutorial
But the gist of it is:
Entity Framework >4.0 supports POCO types that don’t need to inherit from a base class or
implement any interfaces to get persistence. There is also no need for metadata or mapping
attributes on type members, so you can use your existing code as simple entity classes.
An EDMX file that contains the conceptual model is still required. Add a new ADO.NET Entity Data Model to the project.
Using the toolbox, drag entities and associations from the toolbox and design the conceptual model. Simply make sure that the names on your POCO classes match the names of your conceptual entities.
Add entity keys as you would add primary keys in a db. Add associations like foreign keys in a db.
In Solution Explorer, click the EDMX file and then, in the Properties window, clear the Custom Tool property to turn off the automatic generation of .NET classes for your conceptual model.
Right click edmx design area and select 'Generate database from model'. DDL will be produced. Run that to create your db.
Make sure your POCO classes and POCO edmx model are in a separate assembly.
Create your custom ObjectContext derived data context with ObjectSet<T> members like here. Newer EF releases use System.Data.Entity.DbContext and System.Data.Entity.DbSet<T> instead.
You can use dbml too (Linq To Sql classes instead of EF), but you still need to generate your model from scratch, like you'd do with EF.
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.
I'm building an application using EF 5 to talk to an existing Oracle database. I'm not allowed to change any part of the DB schema. I have generated my model from the database using the VS2012 wizard, and all classes are named after their Oracle counterparts.
The naming of objects in the database is QUITE_UGLY_AND_INCONSISTENT, so I'd like to rename the POCO classes and properties. I can easily do that from the EDM Designer. As a result, I get neatly named class and property names, that are mapped to the UGLY_NAMED tables from the DB. I can successfully perform queries and everything works smoothly. Exactly what I wanted.
However, when I need to add new tables to the model, I run the "Update Model from Database" wizard and check the additional tables to import. It suddenly lists my renamed (but still correctly mapped) classes under the Delete tab, saying it can't find them in the database. When I click Finish, my existing classes are unmapped and I have to manually re-map each property to its corresponding DB column... Or roll back to the previous version of the EDMX file from version control.
I'm looking for what you think would be the most elegant solution to this problem, since I need the application to be as maintainable as possible. I strongly favour an approach that lets me auto-generate new classes from the database while preserving the existing renamed objects and their mappings.
Am I overlooking some way to prevent the Update Model wizard from deleting my existing mappings?
Should I use a different approach to renaming the generated classes?
Should I leave the generated classes unchanged and instead construct sanely-named wrapper classes that are exposed to the rest of my application?
Should I refrain from auto-generation and instead go for a code-first approach? This is a very unfavorable option, because I need the time spent on manual model coding and mapping to be as little as possible. Adding objects will be a very frequent task.
Should I perhaps even use a different ORM altogether..?
I discovered the culprit myself: running the "Generate Database from Model" wizard due to a recommendation in an article I read somewhere. It changed all the model's underlying table and column names to SQL Server standard names ([dbo].[Customers].[CustomerID] etc.).
I have my domain split into multiple Entity Framework models. I have some shared entities that span multiple models (named Lookup), however, these are replaced with "using" references using the methods described in Working With Large Models In Entity Framework. However, what makes my case slightly more unique is that I'm also separating these models into multiple databases (one per model).
I'm having a problem inserting one of my shared entities into my common DB. It's failing with the error:
The member with identity
'Harmony.Members.FK_ResidentialAddress_ResidenceTypeLookup'
does not exist in the metadata
collection.
That foreign key that it's referring to does not exist on the "common DB". But I'm also not working with the entity on the other side of the relationship (named ResidentialAddress); nor do I even have the context that would contain the other entity initialized (named MembersDb). However, both models are compiled into the same assembly.
There are no navigation properties going from Lookup to ResidentialAddress. Though there is a navigation property in the other direction (which I won't be persisting - only using in memory).
My MetadataWorkspace for the EntityConnection of the CommonDb context was explicitly initialized with only the SSDL/CSDL/MSL for the data required for that database. I have confirmed there is no references to the foreign key mentioned in that set of schema data.
var metaAssembly = typeof(CommonDb).Assembly;
var schemaResources = new string[]
{
String.Format("res://{0}/Common.ssdl", metaAssembly.FullName),
String.Format("res://{0}/Common.csdl", metaAssembly.FullName),
String.Format("res://{0}/Common.mdl", metaAssembly.FullName),
}
MetadataWorkspace metadata = new MetadataWorkspace(schemaResources, new []{ metaAssembly });
EntityConnection connection = new EntityConnection(metadata, myDatabaseConnection);
POSSIBLE CLUE: It does work when I go into the generated classes and remove all of the EdmRelationshipAttribute attributes along with their paired EdmRelationshipNavigationPropertyAttribute from the related models (MembersDb).
Key questions:
So why is it that Entity Framework is trying to do something with the relationship that is for an entity that is neither in scope and nor will it be affected by the insertion of the record!?
I am happy to have the generated code remove the attributes mentioned above, but I still want the navigation properties to remain. How would I go about altering the CSDL to achieve that?
NOTE: Persistence of the "child" models is not a priority, nor is the integrity of their now cross-DB foreign keys. These databases are persisted using SQL CE but they were originally generated from a single master SQL Server database.
If each part of your model is written to a separate database, then perhaps the edmx files should not know about each other (about entities or relationship to entities that do not belong to them).
How about trying one of the following approaches:
(To end up with same entities classes for each part, but make EF oblivious of connections between them.)
Remove the "usings" from edmx + cancel auto generation and create classes yourself.
Remove the "usings" from edmx + modify t4 template to read more than one edmx when creating the classes.
Copy edmx files aside so you have two sets of edmxs.
3.a. Use set #1 for auto generation of entities.
3.b. Modify set #2 by removing the "usings" and use for generation of repository classes (objectsets).
Let me know if one of these works.
Good luck,
Danny.