Why does Entity Framework insist on renaming columns? - entity-framework

Step 1: import code first from existing database. Existing database has a table with the same name as column.
Step 2: in this scenario, Entity Framework sticks a "1" in front of column name in code.
Step 3: when I try to rename it "by getting rid of 1 in front", I get error
member names cannot be the same as their enclosing type
Why is this limitation on EF and is there a solution that doesn't ruin the database in future migrations (by having that column renamed)?
Being forced to use Column1 just seems really terrible and arbitrary.
Thanks.

As pointed out by #shf301 you cant have a property named the same as the class its in, this is a .NET restriction.
However you can name your column anything else and then tell EF to point to your specific column in the database
eg:
[Column("MyColumn")] // "MyColumn" will be what EF expects in the db
public int FlyingMonkies {get;set;}

Related

Avoid entity duplication with Linq in ASP.NET Core Web API

I want to know the best way of avoiding entity duplication in an ASP.NET Core Web API project.
Imagine that you have a product with a name and manufacturer and you want to make sure if the name is not duplicated. Imagine that a new product with a name came from client (dto) and we need to look if the name (entity) already exists in the database (using EF).
You need to trim the name (name.trim()) for both names from entity and dto
You need to remove all the whitespaces in between (string.replace(" ", string.empty())
You need to change everything to lower case (string.lower())
Finally you need to compare these two
Is there any best practices how to do this without writing all the code? I tried to use string.compare with the compareoptions like ignorecase and ignoresymbols and also the string.equal() with ignorecase option but the EF gives me an alarm that it can not translate the code.
br
I have a suggestion for your approach.
Introduce another column (This can be a primary key with other keys) and save the name with trimming and lowercase when you insert a new record to that table.
Example:
Original Name : Amir Masoud Babaei -->
New Column value: amirmasoudbabaei
And when you insert a new record, do your trimming and lowercase changes and save it to the database. Since it is a primary key, it should throw an error.
So with this approach, you don't need to loop through all the names and validate if the name is already exist.

Entity Framework Core - Computed Column issue

I have an entity class with a column called 'CalculatedId'. This column is obtained from an SQL statement and the column does NOT exist in the database table.
If I run app I get an error telling me that the column does not exist. This error is due to the framework trying to map the column to a physical column.
Below is my mapping code:
modelBuilder
.Entity<Widgets>()
.Property(x => x.CalculatedId)
.HasComputedColumnSql("select top 1 Id from MyTable");
I thought that this would tell EF not to look for a physical column as it's generated.
The only way I can get rid of the error is if I do this:
modelBuilder
.Entity<Widgets>()
.Ignore(x => x.CalculatedId);
Problem there is that the column is totally ignored an not generated at all.
Can someone please connect the dots for me and clarify what needs to be done to make sure that the column is generated but EF does not look for it in the database.
NB: Has to be done in the fluent API, no data annotations.

Change Table and Column Name Mappings Entity Framework v4.3

I've got an application with a working Entity model generated from an existing database. I have to point my application at a new database, with the same schema, except that the table and column names are different.
For example, my current schema has tables named like "Answer". My new schema that I need to point to has the exact same table, except it is named "tblAnswer".
My columns have also changed. Where as a column used to be called "AnswerId", it's now "zAnswerId". Don't ask about the "z" prefix, it's a long story, but it's on every column.
So, what options do I have to point this existing Entity Model (generated from the database) to a new database and adjust the mappings? I've been experimenting with some of the techniques that are used for "Code First" mappings, as outlined in this guide, but haven't had any luck. I simply don't know if this is the right approach, or if there is something that makes more sense.
Suggestions? Thanks in advance.
You can change the database in the web.config file.
Use data annotations to use the different table and column names.
For example:
[Table("tblAnswer")]
class Answer
{
[Column("zAnswerId")]
public int AnswerId { get; set; }
}

How to Use inheritance in EF

I am using EF 4.0 , i have one problem
Table structure in DB is:
Table: Setting--->
Name (PK)
GroupBy
DataType
Table: UserSetting-->
SettingName(PK)(FK)
UserName(PK)(FK)
Value
Table: WorkstationSetting-->
SettingName(PK)(FK)
WorkstationName(PK)(FK)
Value
Now i want to make use of inheritance, because WorkstationSetting and UserSetting inherits settings so any suggestion how to achieve inheritance, i tried but i got error like
"Error 39 Error 3003: Problem in mapping fragments starting at line 1621:All the key properties (Settings.Name) of the EntitySet Settings must be mapped to all the key properties (WorkstationSetting.SettingName, WorkstationSetting.WorkstationName) of table WorkstationSetting.
I see you have in UserSetting and WorkstationSetting a composite PK.
If UserSetting and WorkstationSetting are derived from Setting, they should have Name as PK.
Another comment; in general, it's not recommended to use a name or something "meaningful" as PK since it is less scalable and might cause limitations (i.e. max index size). Use instead an int or uniqueidentifier.
I recommend you to introduce a new field which is SettingId which should be added to all three tables. In EF designer, just add the Inheritance.
Look into table per type inheritance. For example look here. It should help you get started. The idea is that you have a table for each concrete type (as you have) and you map it to an object hierarchy.
Maybe your problem is with the keys. How is your mapping defined? Are the associations between the tables defined in the DB?

stored procedure mapping Entity Framework

We're using a Function Import in an EF4 model to populate an existing entity in our Model. The entity in the model has a Key field of Id which we're struggling to map as our stored procedure doesn't return an Id field. I've tried setting the value in the mapping to a literal value of 0 but that fails with an EntityCommandExecutionException and the following exception text.
The data reader is incompatible with the specified 'Candidate'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.
Short of modifying the stored procedure to return a dummy Id field can anyone recommend what the best approach is for this as the dummy field option feels very clunky to me.
Many Thanks
If you can't return enough data to fully materialize the entity -- and the Id field is certainly going to be required for that -- then you need to change the return type on the proc to be a complex type instead of an entity.
Use another POCO class with the same structure to receive the results of the stored procedure call, here's an example:
string sp = string.Format("EXEC dbo.spComercialesAsociadosActivos {0}", idComercialPrincipal);
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<InfoComercial>(sp);
In this case "InfoComercial" is a POCO class with the same structure as "Comercial", which is tied up to EF code first in the DBContext, then I used this independent class in the viewModel to create a disconnected "Comercial", it's not an ideal solution but will work fine until EF 5 comes with SP support.