Generate specific column in ADO.NET Entity Data Modeling - c#

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.

Related

Inserting FK values in Entity Framework that already exist (identical entries) in one table without updating the primary key of another table

I recently asked a question related to this and found a solution, but realized I may have a bigger problem. If anyone can tell me if I'm able to do what I describe below without making changes to the database it would be greatly appreciated! Note: I'm new to Entity Framework.
I am trying to insert into this table (Agreement Settings) duplicate SettingsId values for a new agreement (associated with an agreementId that is illustrated in the table as a column).
However, a SettingsId is also stored in a table with these columns Algorithm Settings. The Id column represents a SettingsId and is the primary key of this table.
I only want to update the Agreement Settings table (the former table above) with these new duplicate SettingsId values and leave the latter table alone. That way I will have agreements that have duplicate SettingsId guids but only one unique representation of that guid in the Algorithm Settings table.
When I try to insert into the database using Entity Framework:
dataTransferAgreement = (await _dataTransferContext.Agreements
.AddAsync(dataTransferAgreement))
.Entity;
I get brand new guids for SettingsIds returned, although the object dataTransferAgreement has the duplicate guids as properties beforehand (they are replaced). I assume this is because Entity Framework sees these foreign keys in Agreement Settings table and their association to Algorithm Settings table (the primary key) and automatically updates the primary key and thus the associated foreign keys on its own.
I of course can't add the Algorithm Settings table properties to dataTransferAgreement, as that would cause a primary key conflict.
The question: is there any way to manually (or otherwise) insert these duplicate foreign key values into Agreement Settings table without touching the Algorithm Settings table in Entity Framework (code first)? Currently, the entity property that inserts the primary key Id for SettingsId is decorated with [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)], which is used in numerous other places in this project, so I assume I cannot change that.
Also, the entity property that associates this table in the code:
[ForeignKey(nameof(SettingsId))]
public AlgorithmSetting AlgorithmSetting { get; set; }
is not needed in my case (since I don't want to do anything with it), but I can't just remove it due to it being a domain model (again, I'm an Entity Framework newbie so if I'm wrong in any way please correct me).
In your agreements settings table, add a primary key "id", alongside the other two columns you already have. Entity Framework and relational databases aren't going to support the same primary key.
If you need to query the agreement table in the future, you can do so with any column values and just "ignore" the new primary key you added.
Happy to help further if needed.

Why does Entity Framework (EF 6.0) generate a view and not a table for linking tables which causes inserts to fail?

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.

How to change the column names of a mapping table?

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.

Sqlite: Rename columns and datatype

I am using a SQLite database. Since drop/rename/reorder columns are not supported in SQLite (using alter table commands), I am writing customized methods for the following tasks: (taking backup of existing table, then creating a new table with matching requirements and so on..) which is described in several other threads.
The following are the DB operations:
DROP columns
RENAME (columns and datatype)
ADD columns
REORDER columns.
I am wondering in what order should these operations be done? My confusion is mainly around whether drop should come before rename columns or the other way?
Also I need some pointers on how to rename columns including datatype and moving data around?
Any thoughts?
First, create a backup of your database in case something goes wrong during the following instructions.
The order of operations should be CREATE newtable, INSERT INTO newtable, DROP oldtable.
Create a new table with the correct column names and datatypes for each column. Then just do something like this:
INSERT INTO new_table(columns, ...)
(SELECT columns, ...
FROM old_table)
You may need to perform casts on different datatypes if the new datatype isn't directly compatible with the old datatype.
You will need to make sure that the columns you select from your old table are in the same order as defined by the columns in your new table in your INSERT INTO statement.
After data is inserted into your new table, you can then verify that all data has been inserted correctly. Be sure to update any foreign key references in your other tables to avoid any issues with foreign key constraints.
Then you can drop the old table and rename the new table to the name of your old table:
DROP old_table;
ALTER TABLE new_table_name RENAME TO old_table_name;

ADO.NET entity data model generate from database and skip columns

I want to generate EDM from my database file (.mdf), but i don't want to work with all columns. How can i skip these columns from .edmx?
You can't select specific columns at the time of generation. But, if you only want to work with a subset of columns, let the EDM generate the entire table; then in the designer surface you can select the columns you don't need and hit delete to remove them from the model.
One note is that if your database has certain constraints, such as non-nullable columns with no default value, an exception will be thrown if you try to add or update entities without those columns in your model.
You have to do this manually.
Obviously you can map tables as show here, but then you have to go through and manually remove columns. At least this is what I have been told.

Categories

Resources