I am creating an Entity Framework 6 database using the Empty EF Designer Model.
My issue can be duplicated as follows. I have two tables and a many to many association between them.
When I generate the database, it creates a third mapping table, which I expect. However, the names of the columns are unexpected.
CREATE TABLE [dbo].[WordWordType] (
[Words_WordId] int NOT NULL,
[WordTypes_WordTypeId] int NOT NULL
);
Notice that the mapping table has column names that are somewhat redundant and long. The column names include the table name, which is redundant, followed by an underscore, followed by the Key column name.
WordWordType
- Words_WordId
- WordTypes_WordTypeId
I am hoping EF 6 has a way to create the mapping table with column names that don't include the table name and underscore. I need the table to look as follows.
WordWordType
- WordId
- WordTypeId
At the moment you already have the table name in your primary key column name, which is - in my opinion - a redundant information.
If your name your primary key columns simply Id, then EF will automatically name your columns Word_Id and WordType_Id.
In Code First you can use fluent API
modelBuilder.Entity<Word>()
.HasMany(w => w.WordTypes)
.WithMany(wt => wt.Words)
.Map(x =>
{
x.ToTable("WordWordType");
x.MapLeftKey("WordId");
x.MapRightKey("WordTypeId");
});
but since you are using model first I think the only way is to change T4 file which is responsible for generating SQL script. You can find it in Database Script Generation section in your model properties.
Update
see this for debugging T4.
the SSDLToSQL10.tt contains two main section for this, one is Creating all tables on line 150 and another one is Creating all FOREIGN KEY constraints on line 196, they enumerate on Store.GetAllEntitySets() and Store.GetAllAssociationSets() and creating tables and foreign keys in database, debug the T4 file and see where your mapping table is created, I suspect it is in Store.GetAllEntitySets(), then change the generation the way you want.
Related
I have one table that has many fields like ID,Username,Password,Lang,Date,..
When I create Entity Data modeling so all the table field is generated.
I want to generate only specific column like username and password only.
When you generate from database it will generate model for all the columns initially, but you have the freedom to delete the columns that you don't want manually from the generated database EDMX diagram.
Just select the field you don't want and hit 'DEL' key.
Make sure that the fields you delete are nullable ones and also not primary key for that table.
Tables in a many-to-many relationship are best handled by using a relationship (linking) table that only contains a Foreign Key to each table in the relationship. The relationship table itself should not have a Primary Key.
Start Edit (eesh 2017-06-18)
The above statement about the primary key is not true. A primary key should be used. The answer to the question is stated below. I have also changed the Title of this question to better reflect the problem.
Answer to Question: The linking table should have a primary key. The primary key should not be a unique generated Id column as is commonly used for other tables. Instead, it should contain a primary key that is a composite CK (candidate key) made up of the the two foreign keys that are the links for the Many-To-Many relationship. Please see the Stack Overflow question Creating composite primary key in SQL Server
Making this change causes the EF 6.0 to correctly generate the linking table as a table and not a view in the .edmx file. This change fixes the problem I was asking about and the question is answered. Thanks to Ivan Stoev and philipxy for pointing me in the right direction.
Everything below here is part of the original post which is resolved by simply creating a composite CK key for the linking table in SSMS as described above.
End Edit (eesh 2017-06-18)
When created in this fashion the relationship table does not appear in the .edmx diagram, but it is present in the edmx file. Configuring the tables in this fashion makes it easy to query the tables as each table in the relationship has a simple navigation property relating it to the other table.
Some examples of this can be found in the following links:
Entity Framework - querying a many-to-many relationship table
Entity Framework: Queries involving many to many relationship tables
Inserts and Updates should be straightforward as described in the following SO post:
Insert/Update Many to Many Entity Framework . How do I do it?
However, I found when I tried this I got the following error when trying to insert into a model that has a PackageManifest table, a Package table, and a PackageManifestAssignment table that links the two tables:
"Unable to update the EntitySet 'PackageManifestAssignment' because it has a DefiningQuery and no element exists in the element to support the current operation."
PackageManifestAssignment in the above is the linking table that links the PackageManifest table with the Package table. It only contains foreign keys for the PackageManifest and Package tables. There are no no other fields in the PackageManifestAssignment table.
Apparently this works fine when query existing relationships, but attempting to insert fails because EF 6.0 treats tables without Primary Keys as Views and, inserts are not allowed on views. Even though the association table isn't exposed to the programmer in the diagram view, it is present in the .edmx file and EF must insert a new entry in the association table for each new relationship created.
See links below for cause of error:
Entity Framework Error on SaveChanges()
It has a DefiningQuery but no InsertFunction element
Unable to update the EntitySet Table because it has a DefiningQuery and no InsertFunction element exists in the ModificationFunctionMapping element to support the current operation
In the above links an alternate solution is presented to creating a primary key for the table. Adding a primary key to the linking table would complicate CRUD for the tables in the relationship and creating relationship links. Hence, the preferred solution is to modify the .edmx file and make EF think that the table is not a view but is a table (which it is). This works. The instructions are:
Right click on the edmx file, select Open with, XML editor
Locate the entity in the edmx:StorageModels element
Remove the DefiningQuery entirely
Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)
Remove the store:Name property
In my particular case the change looked like:
Before Change:
<EntitySet Name="PackageManifestAssignment" EntityType="Self.PackageManifestAssignment" store:Type="Tables" store:Schema="dbo">
<DefiningQuery>SELECT
[PackageManifestAssignment].[PackageManifestId] AS [PackageManifestId],
[PackageManifestAssignment].[PackageId] AS [PackageId]
FROM [dbo].[PackageManifestAssignment] AS [PackageManifestAssignment]
</DefiningQuery>
</EntitySet>
After Change (Working Version):
<EntitySet Name="PackageManifestAssignment" EntityType="Self.PackageManifestAssignment" store:Type="Tables" Schema="dbo">
</EntitySet>
The drawback to manually making this change is that any time any table in the model is updated in the database and that change is carried over to EF using the .edmx "Update from Database/Refresh" option, the generated file (.edmx) file will overwrite the above changes to fix the error. Those changes will be required to be made manually again. This is both a cumbersome but more importantly fragile. If the change is not made future inserts for entries in the tables that use the linking table will fail. Developers making changes made many months or years down the line could easily forget this step.
Hence, the question is how to be able to keep the desired "easy to use" many-to-many relationship edit made to the .edmx file, without having to modify the .edmx file manually every time the model is updated from the database. Or, alternately is their another technique (marking the table in a certain way) or using a third party library to achieve this?
The relationship table itself should not have a Primary Key.
Every base table should have all CKs (candidate keys) declared, ie any column set(s) that have unique subrow values and that don't contain any smaller column set(s) that have unique subrow values. We can pick one as PK (primary key) and we declare any others as UNIQUE NOT NULL (which is the constraint that PK gives).
The entity id columns of an n-ary relationship/association table, aka linking/association/join table, form its PK, which, consisting of more than one column, is called composite. Per this answer:
HasKey(PackageManifestAssignment => new {
PackageManifestAssignment.PackageManifestId,
PackageManifestAssignment.PackageId
});
PS
Tables in a many-to-many relationship are best handled by using a relationship (linking) table that only contains a Foreign Key to each table in the relationship.
In general relationships/associations are n-ary. They can have attributes of their own. CKs/PKs can include entity or relationship/association (associative entity) CK/PK columns and attribute columns.
Using EntityFramework Reverse POCO Generator v2.26.0 and I cannot find where to change the .tt to stop the column rename when generating the POCOs. I suspect it is in UpdateColumn, which I've updated to just the single line:
UpdateColumn = (Column column, Table table) => column;
But still the columns get renamed from e.g. "Batch_ID" to "BatchId".
Without stopping the column rename, I'm getting the error:
The data reader is incompatible with the specified 'DocumentExport.DataAccess.Databases.Batches.Batch'. A member of the type, 'BatchId', does not have a corresponding column in the data reader with the same name.
How does one stop column renaming during POCO generation?
In the database.tt,
UsePascalCase = false; // This will rename the generated C# tables & properties to use PascalCase. If false table & property names will be left alone.
While this accomplished suppressing column names, it also affected table names and possibly other things.
I'm a bit of a noob with DAO and SQL Server and I'm running into a problem when I'm trying to insert values into two tables that have a relation. The table Photos has a gpsId field which has a foreign key relation with the id field of the GPSLocations table. I want to create a new Photos entry linked to a new GPSLocation, so the code looks something like this:
gpsRow = dataset.GPSLocations.AddGPSLocationsRow("0.0N", "3.2W");
dataset.Photos.AddPhotosRow(#"c:\path\file.jpg", gpsRow);
tableAdapterManager.UpdateAll(dataset);
However this results in the following error:
A foreign key value cannot be inserted
because a corresponding primary key
value does not exist. [ Foreign key
constraint name = photoToGps ]
I'm using SQL Server CE. Is my understanding correct that the TableAdapterManager should be handling this hierarchical update? I just dragged these tables onto the XSD view and relied on its automatic creation of the wrapper classes. Do I need to change anything about the relation (eg to make it a Foreign Key constraint)? I've noticed that under some circumstances the gps id is positive and sometimes negative, is that relevant?
EDIT:
I've also ensured that the update property is set to CASCADE, which results in the same error. Hierarchical updates are set to true and there is a foreign key constraint between the two tables in the designer.
It's just the configuration of your data set. Doubleclick the relation beween the tables in the Visual Studio's dataset designer, choose Both Relation And Foreigh Key Constraint option and in the Update Rule field choose Cascade option and that must be it.
Some information about the subject is in MSDN, you can look here http://msdn.microsoft.com/en-us/library/bb629317.aspx and go to the related topics.
I've managed to track down the source of this problem, which boils down to a limitation of SQL Server CE compared with the full SQL Server. It turns out the major hint that something wasn't right was because the ids were negative. The ids are negative in the DataSet before the row is inserted into the database, at which point it gets resolved to a positive index. The fact that it wasn't becoming a positive index happened because the TableAdapterManager normally does a batch statement of INSERT followed by a SELECT to update the id. However, SQL Server CE doesn't support batch statements, so this requires extra code to be written so that we simulate the SELECT step by responding to the RowUpdated event. This MSDN article explains the steps.
Did you enable Hierarchical Updates as described here?
Is there a foreign key constraint between the two tables (there should be a line on the XSD designer connecting them)? Since your fields are named differently it might not have been automatically added when you dragged the tables to the design surface.
Since the column photoToGps (foreign key) depends on the primary key (id), you cannot add a photoToGps unless there is a corresponding id present. So what you need to is individual updates, instead of doing an UpdateAll. First update the GPSLocations table, and then the other table. That way, you will have an id existing before you add a photoToGPS for it.
I have a Parameter table in my sql server db. This table contains 20 or so fields, but only ONE record. This table will always contain one record, and also contains no Id or key field.
How do you map this with NHibernate?
What about creating a column that would always hold 1 (or whatever other value). I believe that if you want to be able to update your columns you will need an ID.