Code First from database with existing Designer from database - entity-framework

We've been working for along time using EF Designer from database, so switching to another approach is not an option for us.
Due to a legacy version of our app i need to create relationship between tables on EF level for the current version, so those relationships don't exist in the schema.
I understand that i can do do that using Code First from database approach, but the problem how do i map the fields and make these entities part of the main datacontext which we already extended its functionalities using another partial class.. the main problem now is just mapping the new entities fields
i can't create OnCreatingModel in a new datacontext class since it does exist in the auto generated datacontext class.
to sum up.. is there anyway to use both approaches on the same DAL? taking in mind modifying auto-generated classes is absolutely not an option.
Thanks!

Related

Development process for Code First Entity Framework and SQL Server Data Tools Database Projects

I have been using Database First Entity Framework (EDMX) and SQL Server Data Tools Database Projects in combination very successfully - change the schema in the database and 'Update Model from Database' to get them into the EDMX. I see though that Entity Framework 7 will be dropping the EDMX format and I am looking for a new process that will allow me to use Code First in Combination with Database Projects.
Lots of my existing development and deployment processes rely on having a database project that contains the schema. This goes in source control is deployed along with the code and is used to update the production database complete with data migration using pre and post deployment scripts. I would be reluctant to drop it.
I would be keen to split one big EDMX into many smaller models as part of this work. This will mean multiple Code First models referencing the same database.
Assuming that I have an existing database and a database project to go with it - I am thinking that I would start by using the following wizard to create an initial set of entity and context classes - I would do this for each of the models.
Add | New Item... | Visual C# Items | Data | ADO.NET Entity Data Model | Code first from database
My problem is - where do I go from there? How do I handle schema changes? As long as I can get the database schema updated, I can use a schema compare operation to get the changes into the project.
These are the options that I am considering.
Make changes in the database and use the wizard from above to regenerate. I guess that I would need to keep any modifications to the entity and/or context classes in partial classes so that they do not get overwritten. Automating this with a list of tables etc to include would be handy. Powershell or T4 Templates maybe? SqlSharpener (suggested by Keith in comments) looks like it might help here. I would also look at disabling all but the checks for database existence and schema compatibility here, as suggested by Steve Green in the comments.
Make changes in code and use migrations to get these changes applied to the database. From what I understand, not having models map cleanly to database schemas (mine don't) might pose problems. I also see some complaints on the net that migrations do not cover all database object types - this was also my experience when I played around with Code First a while back - unique constraints I think were not covered. Has this improved in Entity Framework 7?
Make changes in the database and then use migrations as a kind of comparison between code and the database. See what the differences are and adjust the code to suit. Keep going until there are no differences.
Make changes manually in both code and the database. Obviously, this is not very appealing.
Which of these would be best? Is there anything that I would need to know before trying to implement it? Are there any other, better options?
So the path that we ended up taking was to create some T4 templates that generate both a DbContext and our entities. We provide the entity T4 a list of tables from which to generate entities and have a syntax to indicate that the entity based on one table should inherit from the entity based on another. Custom code goes in partial classes. So our solution looks most like my option 1 from above.
Also, we started out generating fluent configuration in OnModelCreating in the DbContext but have swapped to using attributes on the Entities (where attributes exist - HasPrecision was one that we had to use fluent configuration for). We found that it is more concise and easier to locate the configuration for a property when it is right there decorating that property.

Is there a way of avoiding 2 repository objects for the same database table?

Im currently working in a team that uses EF as the ORM of choice.
We have a common project that contains many EDMX files.
The reason for this is to keep the EDMX files small and manageable while also allowing them to focus on a conceptual set of tables on the database.
Eg
Orders.edmx
Users.edmx
Trades.edmx
These all point to a different set of tables on the same db.
I now need to add the user table to the Trade.edmx file. Since the user table is already in the user.edmx file, this creates the same User type twice under a different namespace which means I would need 2 UserRepository objects.
Common.data.trade.User
Common.data.users.User
Is there a way of avoiding 2 repository objects for the same table?
Any suggestions would be greatly appreciated
If you are using POCO generator you can update template for Trades.edmx to not generate new User class and its context template to use User class from Users namespace. EF matches POCO classes with entities in designer only by the class name (namespace is omitted) so it will work.
The disadvantage is that you have User entity in two mapping files and you must update it in both files or your application throw exception at runtime.
The reason for this problem is your architecture - at the beginning you wanted separated models but know you want to combine entities from different models. Those are contradicting requirements. Either use separated model where Trade knows only userID without any navigation property (like if it is defined in another database) or move all entities to single EDMX to support your new requirements.

Defining business objects in Entity Framework

Trying to understand Entity Framework. My approach is database first. However I would like to define other entites in the model that is closer to my business objects. I guess I could write queries in the db and include them in the model. But I would also like to define entirely new entities in the model though they would be based on underlying tables in the db. How do I do that - does anyone know a tutorial?
Regards
Bjørn
db Oldtimer, EF Newbie
Database first means that you have existing database and you can either create model by updating from database or manually. You can use wizard to create initial model and modify it manually to define new entities but you must not use update from database any more or some of your changes will be deleted. Also your custom modifications must follow EF mapping rules (for example it is not directly possible to map multiple entities to the same table except some more advanced mapping scenarios like splitting and inheritance) and some of them (custom queries) must be done directly in EDMX source (XML) because designer doesn't support them - this requires more complex knowledge of EF mapping and it will be definitely hard for newbie.
You can check specification of that XML. For entities mapped to custom queries you will have to use DefiningQuery element in SSDL part of EDMX.

Which type of Entity generator to use?

I am writing my first WPF and EF application. I am using SQL CE database and I have added few tables to the DB. The EF diagram is generated and now I want to generate the classes. I am new to EF and MVVM both.
When I right-click on a Table diagram, it gives option "Add Code Generation Item..". On selecting it, there are two options:
Add Entity Object Generator
Add Self-Tracking Entity Object Generator
I want to know what is the difference between the two. Which one should I use? I also want to know which one is latest and what is POCO?
A POCO is a Plain Old CLR Object... a simple class that has only properties.
http://en.wikipedia.org/wiki/Plain_Old_CLR_Object
There are 3 approaches that the Entity Framework delivers.
Model first (you create a model in visual studio and generate the database)
Database first (thats what you do, you generate a model from a existing database)
Code first (the newest one, you just write you POCOS and the entity framework generates the database)
I think it is enough to generate the diagram from database. The context and models should be available after this.
Neither of those is the POCO generator. The best way to get that is to install Entity Framework 4.1. You'll then see some new options in the list to add a code generation item.
I'm a pretty big fan of the DbContext/POCO generator added in 4.1 as the code it creates is VERY easy to work with compared to the older stuff, and it works well in a DB First setup like you're using (which is also what I use).
You can give this code generator a try:
http://salardbcodegenerator.codeplex.com/
It generates data annotations and implements INotifyPropertyChanged for CodeFirst approach.

Entity Framework - Foreign key constraints not added for inherited entity

It appears to me that a strange phenomenon is occurring with inherited entities (TPT) in EF4.
I have three entities.
1. Asset
2. Property
3. Activity
Property is a derived-type of Asset.
Property has many activities (many-to-many)
When modeling this in my EDMX, everything seems fine until I try to insert a new Property into the database. If the property does not contain any Activity, it works, but all hell breaks loose when I add some new activities to the new Property.
As it turns out after 2 days of crawling the web and fiddling around, I noticed that in the EF store (SSDL) some of the constraints between entities were not picked up during the update process.
Property_Activity table which links properties and activities show only
one constraint
FK_Property_Activity_Activity but
FK_Property_Activity_Property was
missing.
I knew this is an Entity Framework anomoly because when I switched the relationship in the database to:
Asset <--> Asset_Activity <--> Activity
After an update, all foreign key constraints are picked up and the save is successful, with or without activities in the new property.
Is this intended or a bug in EF?
How do I get around this problem?
Should I abandon inheritance altogether?
Not a but but a poor visual designer.
Its generally best to simply manage the Entity XML by hand.
No inheritance works well for many situations.
Basically I use the update from database in the visual designer but knowing that the designer has its quirks. I have simply used the update from database to stub out the basics of what I want. Then I go into the Entity XML my self and clean it up the way I want. Just of note Complex types are a pain with the designer. If you plan to use complex types get ready to learn your Entity XML well.