Entity Framework conflict with same table name from different databases - c#

I am using Entity Framework 4 with MVC 3 in Visual Studio 2012 (C#).
I am using database first; there are two separate databases each with its own namespace and with two separate edmx files. Each database has a table with the same name and fields (but different content). When I added the second table I started to get compile errors.
Ambiguity between 'Interface.CodeFormStatus.FormStatusCodeID'
and 'Interface.CodeFormStatus.FormStatusCodeID'
There seem to be some complex workarounds or I could rename one of the tables. Is there not a straightforward solution as this must be a fairly common issue.

I ran into a situation where I had two databases (one an older version of the other) and I needed to integrate both into a single project. Naturally, almost every name conflicted.
I created two separated edmx files for each database, and put each in its own namespace for clarity. I then edited each entity name to reflect which database it was coming from - (e.g. "Activities", which was in both, became "v13Activities" and "v14Activities").
For operations which were to be mirrored between both databases, I wrote a wrapper that included both contexts. This made my code was much less repetitive, and it had less synchronization issues.
Hope this approach helps someone else - it seems like this is an obscure question, and this answer was one of the top results on Google!
Update: In EF 6.1+, there is another solution. You can have "conflicting" names, and separate them with simple namespacing when using the "Code First From Database" option. I would advocate for this solution going forward, as the old XML .edmx style is going to be phased out starting in EF Core.

This worked for me. Just click on the table in the designer (the graphical version not the code) Then in the properties next to the, "Name" attribute you can change the name to something different. This will just change the name within the designer and used more as an alias throughout the application.

If you don't have many tables with the same name, then you could edit entity name in designer (your .edmx file).
So, just double-click a name of one of your CodeFormStatus entities and make it different (for example, change it to CodeFormStatusOther)

Related

Is it possible to have two Entity Models from two databases in one project?

I used to have one Working edmx model with WCF service.
Then I've added another Entity Model pointing another connection.
I will try to explain in nutshell what is happened in app.config.
there is still being one connectionString with old name
but now it points new entity model
but initial catalog is not even updated to new one and points to old one
I'm sure that something is wrong here. And I also can't find can I change / edit it from properties.
Is it possible to have two Entity Models in one project? If so then what could cause such things in my situation?
I had a similar problem a while back where I had two models in one project which worked fine at first. My problems started when I had to reference the same table in both models, specifically as the generated POCOs were in the same project.
In the end, put the two edmxs in separate projects. Julie Lerman in this tutorial says this is a perfectly fine thing to do.
Yes, you can have many .edmx models in one project; what you have to do is put each Model.tt in different projects and remove them from the project where are the .edmx models. So you have something like this:
- com.DataAccessLayer
- com.Entities.Model1
- com.Entities.Model2
Each model uses different connection string if you want to connect to different data bases.
Here you can find how to separete Model.tt from Model.edmx
http://nullablecode.com/2013/09/splitting-entity-framework-model-classes-separate-projects/

EF 5.x DbContext Generator - Namespace Issues

I'm trying to update a project to work in ASP.NET MVC4 using EF5(Database First approach as there is an existing db). I'm doing this with VS2010.
I am following the steps in this example.
These are the steps that I'm taking:
Set up a new MVC4 project simply called Project.NET
Create the Entity Data Model as ProjectModel.edmx
The connection string is saved as ProjectEntities
The model namespace is set to ProjectModel
Add an EF 5.x DbContext Generator item called ProjectModel.tt
So after all that, it has created the classes to be used by EF; the problem is that these classes are all created with the project's root namespace, rather than the namespace I have provided it.
If I open up any of the generated classes, I get a list of errors that are fixed by manually changing the namespace to ProjectModel
I'd appreciate any thoughts.
Update:
This is a screenshot showing the project structure, an example of the generated code, and the compiler errors.
What's odd is that it only seems to throw an error for a namespace based on the structure, so in the image Project.Models as the namespace creates an issue, but if I type in anything else such as ProjectModels or Test the errors disappear. I can change the the namespace on all the files, sure, but every time the model changes and is updated, the namespace will be reset and the errors return.
This question seems to be the same issue as the one I am having, but unfortuntely, the only answer given advised checking references; I believe mine are fine as System.Data.Entity and EntityFramework are present.
Update 2:
If I don't select all tables to during the code generation no namespace issues appear. I'm currently updating the model in 20 table intervals, with 400 tables though, I'd rather figure out what the actual issue is. I'm assuming it is due to the structure or name of one or more tables, but I'm not sure on whether or not there are any specific rules with regard table structure or naming with regard to EF.
Looks like your project is targeting .NET 2.0. Right-click on your project and choose Properties. make sure Target framework is set to .NET 4 or later.
It appears as though one of the tables which is called System was conflicting with the .NET System namespace. I guess I'll just have to change the table name to something else.
If you are adverse to making changes to your data schema, you can configure Entity Framework to map the table name to a different type/class. Something like this may help.
I achieved to set a custom namespace for the generated classes by setting the Custom Tool Namespace field in the .edmx model properties, and also in the properties of both the .tt files under it, using the Properties window.

Prefix tables with entity framework automatic code migrations

I started a new project C#, and I used the "enable-migrations" command in the package console window. This naturally added migrations to my project. I then set automatic migrations to true, so that as I call "update-database" it will create my tables for me with all keys and that.
The only problem is that I have multiple websites where want to do this, which all use the ASP.NET membership provider to login. Which through automatic code migrations create a bunch of account tables for me to use. But the tables are all called the same, so if I do this targeting the same database for different sites they will overwrite eachother. So the question I got is this: How can I specify a prefix for my tables created by the entity framework?
I've seen several ideas on how to do this while searching, but they didn't work for me (the necessary properties wasn't there for some reason and so on.)
Thank you
Xenoxsis
I'm not sure how do you plan to do just that - if I'm getting it right you'd want to keep one database (shared) in between number of web sites - yet, have each site has its own membership tables, named differently, with different prefixes, right?
First problem is that for each Db/table name change - you need a 'code to match' - i.e. code first entities and code, the 'migration table' in the Db - and tables are all in sync - so it could all work together as it should. In that sense, just changing script or table names in Db won't work. It has to be done at the level of attributes (as #Steven suggested) or fluent configuration.
Which in your case, it means that somehow you'd need to 'build' separate configurations for each site, deploy them separately (code) to each site - and build one mega Db that contains all the small variants of each merged together.
That's going to be tough to manage - but you could try (what I described above) - I have no idea if it'd work (as this requires lot of 'infrastructure' to try this one) - but maybe along these lines...
put Table attributes (or via fluent config)
Build code - 'vary' the Table names for each - and rebuild (ideally you might need to employ some tool, code-generator to do this automatically in a batch - i.e. you build, copy files externally, change names and repeat)
Build 'migrations' for each case (Table name) also - save migrations
as files - and also do Update-Database -Script to save the actual
scripts for each case (important).
Save each migration - or we can
say a 'script' to represent.
Once done - you'd need to merge the
migrations - scripts - into one big master script - i.e. remove the
identical set of tables (leave just one of course) - and copy all
different sets for membership tables.
Remove the migration table
from the database - as that'd surely be out of sync and won't let you
do anything (or there is also a flag in code I think to just ignore
that, don't have it right now). For details see below in my other
post.
Deploy one master Db - using script you created
Deploy the
specific code - to each of the sites.
Pray it'd all work :)
There must be something smarter - but on the other hand, migrations are not made to work for such scenarios, so it's going to be hard if not impossible to pull this off.
Some general info that might help...
How to synchronize migrations with existing databases - geared toward production scenarios, maintaining Db-s and CF to match. It's not exactly what you need but has a detailed description, possible ways to resolve this which I wrote a while ago...
MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"
To summarize...
What works for me is to use Update-Database -Script
That creates a script with a 'migration difference', which you can
manually apply as an SQL script on the target server database (and you
should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...(more inside)...
I don't know of anyway to make Entity Framework do this automatically across all entities. But you could force a table name, or schema using attributes or fluent API to get the desired effect. For example:
[Table("[put prefix here]_Users", Schema = "[put schema here]")]
public class User {
// ...
}

Editing T4 files to customize entity class names and output file names

I'm using Entity Framework Reverse Engineer Code First on an existing database. The classes are created properly but I need to change the entity names. I want to prefix every entity class with "EpiFlex". If a SQL table name is Users, the resulting entity should be EpiFlexUsers and the output file should be EpiFlexUsers.cs.
Is there a tag of some sort that I can add to the beginning of the T4 files to have that prefix added automatically or do I have to painstakingly go through each file and put the prefix ahead of the auto generated code?
Or maybe I'm totally missing the point. Is there another way to specify custom naming of the entities?
There doesn't seem to be any quick and easy way to do this. However, Programming Entity Framework 2nd Edition is an excellent book that I've come to consider absolutely essential if you're going to really get into entity framework. This book also has a lot of help on editing the T4 files. I haven't digested the complete section on T4 editing yet so maybe I'll still find something that shows how to very easily do what I want.
Here is a link to the book. http://shop.oreilly.com/product/9780596807252.do

Change entities and properties names in Database First

I'm starting a new application that must use an existing database that use some naming conventions that are really annoying in .net (table names start with several trigrams that specify the business domain of the table, column names start with the tables trigram, trigrams are in uppercase and separated by underscores, etc.,).
What I'd like to do is to write a simple renaming rule (this is as simple as finding the last underscore and take everything after that) and apply it in Entity Framework. I don't really want to edit the names one by one in the editor, especially because the database might change and I don't want to do it several times.
I'm using Database First (as the database already exists and it is "the master"), and EF 4.x DbContext Generator and it works really great out of the box (with badly named classes and properties though).
I edited the T4 templates in order to rename the generated entities and properties, but when I try to perform any request, the DbContext object can't find the table that matches with the entity I'm trying to request and I get this exception :
The entity type [Entity Name] is not part of the model for the
current context.
This is obvious why it doesn't find the table : nothing tells it how to match the entity name and the table as I changed it on the fly.
I read that I can add instructions in the OnModelCreating(DbModelBuilder modelBuilder) method but this is not used in Database First (and the default T4 template adds an exception in it, just in case).
So now I'm stuck, I don't know how to specify that matching.
Here are several ideas I have but not sure if it's correct or doable :
Using the "plural / singular" API to change the name of the Entity ? Sounds like a dirty workaround. But it might work (didn't try though).
Finding a way to edit the EDMX file on the fly.
Editing the EDMX afterwards but it might complicate the process (edit in the designer, then execute a tool to alter the EDMX, then run custom tool to regenerate entities and DbContext... while today I just have to edit in the designer).
Using Code First (as it seems easier to use different entity names than table names, through attributes or instructions in the DbContext class), but it sounds like it would not be more complicated to use it with an existing database.
Any idea ? Or did I miss something ?
You won't be able to use a T4 transform for this, as you want to change the content of the actual .edmx file to map your store entity names (with the obnoxious prefixes) to your sanitized conceptual entity names.
Instead, you're better off writing an application that takes an .edmx file as input and sanitizes the names under the conceptual model tag and modifies the mapping names to reflect the sanitized names. I understand that this is your third option and that you wanted to avoid this if possible, but this is the most straightforward way to go about it. Bear in mind that you'll only have to run this tool when you add new tables or columns.

Categories

Resources