X Already contains a definition Y with EntityFramework? (simple database) - c#

I have 3 tables in my MS SQL database and I have added a EntityFramework(latest) to my project where I have imported these 3 tables. The first problem was that no Entities was built so I changed "Code Genereation Strategy" from None to Default.
After build I get
X Already Contains a definition for Y
on all properties of the entities.
When looking closer it have generated a partial ex Users.cs and one partial User in in the MainModel.Designer.cs?
Why is it generating User.cs? I have a similar setup in another project and the EF is set with the same settings, there is no User.cs?
Edit1 : I can see one thing that differs and thats Use Strong Spatial Types that is set to False in the failing project, it is however not possible to set it to true(grayed)?

You should either use None code generation strategy for your .edmx file. Or remove MainModel.tt and MainModel.Context.tt templates, which generate model entities and context.
If you use Default code generation strategy, then entities and context will be generated into MainModel.Designer.cs file. That would be standard entities, inherited from EntityObject, context will be inherited of ObjectContext. With Entity Framework 5 we have POCO entities generation. And whole generation is done in T4 templates, which generate context, inherited from DbContext, and POCO entities without some base type (well, object only).
When you have both templates and enabled code generation in edmx designer, then two sets of entities will be generated. That's why you have names conflict.

Right Click the Entity model.
Go to properties and remove the default name in the "Custom Tool".
Assign the edmx in the model.tt and model.context
Build and execute it you will be free from error.

Related

Avoid re-modelling objects from a base EF Core 3.0 model when inherritting the context

The goal
My goal is to create a hierarchy of DbContexts each one residing in different assembly. Whatever references are required are established correctly so that the C# code compiles successfully.
The scenario
Let's say I create a db context, e.g. DbChild, inheriting from a base one, say DbBase.
The base context has some entities defined in OnModelCreating(). A migration for these entities is created and successfully applied to the database, thus the db schema contains the DbBase model mapped.
Needless to say DbChild uses the very same connection string and therefore the same database (I tried a number of ways to supply the connection string, the last one specifying it directly in optionsBuilder.UseSqlServer("<conection string>");).
Actual result
Creating a migration for the child context, however, includes the base model as part of the child one, which results in duplicate SQL objects in the DB.
Required result
A "clean" migration including only SQL objects (EF entities) from the child context is required.
Any ideas how to achieve this?
Thanks in advance.
PS: calling Ignore(...) in OnModelCreating() might be a workaround but it needs everything referenced in DbBase to be referenced in DbChild which is not an option.
PS2: Totally ignoring the base model while create the child one is not an option too - child uses an entity from base as a relationship.
EDIT: The snapshot <ContextName>ModelSnapshot.cs contains a "copy" of the model which gets updated with each migration. This is where every migration starts up. In complex models, however, it would be much easier, and what is much more important - safe, to have the snapshot file generated programmatically out of the existing database instead of copying, changing namespaces, renaming so as to have the context name reflected etc.
So, the questions may be transformed to "How to generate database snapshot when applying the first migration?".
Any ideas are welcome.
When creating a new derived context, after setting up the DB connection string but before adding any derived types to the context, you should create a migration that saves the snapshot of the pre-existing base context types.
In EF6, this would be done by creating a migration with Add-Migration PreExisting –IgnoreChanges. This produces a migration, where the internal model contains an updated snapshot, but the Up and Down methods of the migration are empty.
I'm not up to date on whether EF Core does support the -IgnoreChanges switch currently. According to What is the equivalent of the -IgnoreChanges switch for entity-framework core in CLI?, an alternative is, to manually clear the Up/Down methods after creating a migration.
Only after the first snapshot migration is created, start with adding additional entities to the derived context and creating migrations to add them to the database etc.

The call is ambiguous between the following methods or properties: 'EntitiesLan.EntitiesLan()' and 'EntitiesLan.EntitiesLan()'

I have the following code and don't know why this error is thrown.
using (var context = new EntitiesPlesk())
{
/////Some Code
}
using (var context = new EntitiesLan()) // Error Line
{
/////Some Code
}
I am using .sdf Database file for edmx model (EntitiesLan)
Please help me where i should change to get rid of this error....Thanks!
The problem is not with your code, the problem actually is that you are trying to regenerate your edmx in higher version of EntityFramework. One possibility could you might be modifying your old project of VS2010 in VS2013.
With previous version of Entity Framework a model created with the EF Designer would generate a context that derived from ObjectContext and entity classes that derived from EntityObject.
Starting with EF4.1 we recommended swapping to a code generation template that generates a context deriving from DbContext and POCO entity classes.
In Visual Studio 2012 you get DbContext code generated by default for all new models created with the EF Designer. Existing models will continue to generate ObjectContext based code unless you decide to swap to the DbContext based code generator.
Source: MSDN
Solution
Sergey Berezovskiy has described the solution as following, in THIS SO post.
You should either use None code generation strategy for your .edmx file. Or remove MainModel.tt and MainModel.Context.tt templates, which generate model entities and context.
If you use Default code generation strategy, then entities and context will be generated into MainModel.Designer.cs file. That would be standard entities, inherited from EntityObject, context will be inherited of ObjectContext. With Entity Framework 5 we have POCO entities generation. And whole generation is done in T4 templates, which generate context, inherited from DbContext, and POCO entities without some base type (well, object only).
When you have both templates and enabled code generation in edmx designer, then two sets of entities will be generated. That's why you have names conflict.
You can find THIS SO post useful in order to clear your understanding and resolution of this issue.

EF Poco Generate for specific table

It is possible to generate a POCO class for one selected table in entity framework.
There are few tools that does that, but it does generate for all the table,
The primary reason i am asking this is to generate a POCO class for a single table, and add attributes to it manually, and the all i need to do is to attach it to DbContext as a property :).
As for example using Package-manager, they way it is done to add migration
generate-poco TableName FileName.cs
You can use the ADO.Net wizard to generate the POCO classes for you from the database. The wizard will generate one partial class per table with properties that match your field names. Here is what I've done in the past when I wanted to add a new large table to an existing code first context.
Add->New Item -> ADO.Net Entity Data Model
Move the generated POCO classes to some other folder (and edit the namespace)
Delete the rest of the extra stuff (I.e the .edmx file and generated context)
Add the DBSet to 'your' DBContext
If you are using EF migrations
add-migration
update-database
There are a lot of extensions for visual studio for that.
EF 4.x POCO Entity Generator for C# Free (try this one and you only need to map the table)

How to Convert a normal class.cs to DataModel.dbml

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.

Entity Framework - Inserting entity with multiple models and databases

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.

Categories