I'm trying to create an EF model based on an existing MySQL Database.
Upon creating an entity, I map it using:
[Table("databaseName.tableName")] or :
modelBuilder.Entity<Lang>().ToTable("tableName") in OnModelCreating.
The issue I have is that the table names could have an unexpected prefix.
What I want to do is, without knowing the prefix, search for any table in the database that:
(Something like)EndsWith("tableName") use it, or:
which name matches a Regex.
Is this doable? The alternative would be to ask the user for the TablePrefix specific to his/her database and work with it (modelBuilder.Entity<Lang>().ToTable(prefix + "tableName") but that would be quite inconvenient. Since the prefix is the only thing that can change from database to an other, it would be really helpful to be able to detect tables by their name.
You can't query the database in OnModelCreating, but you can use the Connection String to open an ADO.NET Connection to the database and run a query to retrieve the table names and construct a mapping between the Entity types and the table names.
Related
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.
(Sorry for my bad English)
I have imported an access database to a C# winform project (.net 4.0) in visual studio 2013. It automatically creates a .cs file with a DataSet, TableAdapter and a TableAdapterManager.
I import data from the database to the DataSet, without error. I succeed to manipulate data, and save change to the database with TableAdapterManager.UpdateAll().
But now I try to insert new data, with relation between tables.
For example, a database like mine
Parent table :
autonum key
string parentname
Child table
autonum key
string childname
int parentKey
First try :
I create a new record with parentTable.AddparenttableRow(data ...) and get a parentRow.
I create a new record with childTable.AddchildtableRow(parentRow, data ...)
But if I call TableAdpaterManager.UpdateAll(), I get an error "can't add or modify a record because a related record is required in parentTable" (not the real message, it's a translation). I think that AddchildtableRow create the correct relation. And another problem appears : because of the error, the database isn't modified (which is good), but the records I had add, are always in the table of the DataSet.
So I try another method : TableAdpaterManager.tablenameTableAdpater.Insert()
First I insert a parentRow without any problem. But when I want to insert a childRow, the insert function asks for the parent key. But I don't have it (the insert parent call doesn't return the key).
My question is : how can I use the DataSet, TableAdapter and TableAdapterManager to insert records in the DataSet AND in the database, and with a transaction (if there is an error, the data won't be written to the database, and won't be added to the DataSet) ? And actually, how to correctly use these classes ?
Look up the typed dataset code. Switch between the default TableAdapterManager.UpdateOrderOption.InsertUpdateDelete to UpdateInsertDelete (msdn). For hierarchical updates you have to merge new values for your identity columns (msdn). Also see this post. The way ADO.NET deals with preventing collisions with it's disconnected dataset, it assigns negative IDENTITY column values, because it wouldn't know a possible positive number that IS NOT a collision as it's disconnected. Also managing a ##identity crisis with parent-child relations. The typed dataset technology also had issues with circular table references.
I have a database with several tables and I am using the following query to return a record that matches a string(Name).
In the MHP table there is a Name field(primary key), Num_Sites and a few more, but these are the only ones I am concerned with.
In the MHP_Parcel_Info table there are many fields with one of them being Name(foreign key). There is a parcel_id field and in some case there may only be one parcel for one name, but there may also be many parcels for a Name.
As it is now my query will return one of the rows for instances where there are multiple parcels for a name.
What I would like to do is: if there is more than one parcel for a Name, have all the parcels put into a list(so I can display in listbox on form).
My SQL skills are limited and I don’t know how I would go about doing something like this.
SELECT MHP_Parcel_Info.*, MHP.NUM_SITES FROM MHP_Parcel_Info INNER JOIN MHP ON " +
"(MHP_Parcel_Info.MHP_NAME = MHP.MHP_NAME) WHERE MHP_Parcel_Info.MHP_NAME='" + strValue + "'"
This is not something you can do directly in SQL. There's no way to select data in a parent/child structure in a SQL query - you have to do that as a post-processing step.
Since this is tagged as C# and Winforms I'm assuming this is from inside a .Net app. You will need to execute the query as you have it above, then in C# you can use the LINQ GroupBy extension method on the result to group the results into a list of IGrouping objects which use the name as the key, and has all of the parcel info as the items in the list.
Even better, if you are using (or can use) LINQ to SQL or Entity Framework you can just write a linq query that fetches the data from the database and does the grouping all at once.
My application is based on Entity Framework. I am offering users to query a particular table by saving their queries in another table. For example, TopQuery table in database stores all the queries which are popular among users.
These queries are performed on table "TableData"
For test purposed, I have tried the following and it works. The only problem is that it returns all columns where as I would like to use columns that are mentioned by users in their queries.
string queryString =
#"SELECT VALUE table FROM TestEntities.TableData AS table where table.col1 = 'test'";
ObjectQuery<TableData> productQuery2 =
new ObjectQuery<TableData>(queryString, context);
My problem is that if user stores a query in database like this, it doesn't work.
SELECT table.col1, table.col2, table.col3 FROM TestEntities.TableData AS table where table.col1 = "test"
I get the exception: The specified cast from a materialized System.Data.Objects.MaterializedDataRecord' to'TestEntities.TableData'type is not valid.
I have also tried this without any luck.
"SELECT it.col1, it.col2 FROM TableData WHERE it.col1 = 'test'"
What should I do in such case?
Regards,
You will never get ObjectQuery<TableData> once you try to select only subset of columns. Using ObjectQuery<TableData> works only when you select whole entity as your first query did - that is a strongly typed approach enforced by Entity framework.
ESQL doesn't support projection in the way Linq-to-entities does (by allowing you to project to a new anonymous or non mapped type). When using projection with ESQL you must work with ObjectQuery<DbDataRecord>.
I'm writing a quick app using LINQ to SQL to populate a db with some test data and had a problem because one of the tables had no primary key as described by this bloke Can't Update because table has no primary key.
Taking the top answer I added the IsPrimaryKey attribute to an appropriate column and the app worked even though the I haven't changed the db table itself (i.e. there is still no primary key).
I expect it will be ok for my current intentions but are there any side effects which may come from having a table without a primary key seen as having one by the LINQ object?
(I can only think it might be a problem if I tried to read from a table (or populate to a table) with data where the 'primary key' column has the same value in more than one row).
When using an ORM framework, you can simulate keys and foreign keys at ORM level, thus "hiding and overriding" the database defined ones.
That said, that's a practice that I wouldn't recommend. Even if the model is more important than the database itself, the logical structure should always match. It is ok doing what you did if you're forced to work with a legacy database and you don't have the possibility to fix it (like adding the PK on the table). But try to walk the righteous path everytime you can :)
Tables without a PK = Pure Evil.
Basically if all the table updates go through the LINQ object you should be fine. If you have a DBA that decides to modify data directly though SQL then you can quickly run into issues if he duplicates a row with the same PK value.