Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map table names and column name different from model in onmodelcreating method in Entity Framework -6?

I have my database with table names starting with "tbl" prefix and column names like "ua_id" which are understandable in context of project but problematic if used in a model i.e names should be readable or meaningful(not like indicative names defined in database).

So I want to map them in my onmodelcreating method but I have no idea about it. I studied it in following blog:
http://weblogs.asp.net/scottgu/entity-framework-4-code-first-custom-database-schema-mapping but this is for EF 4.1 and method doesn't work for EF 6.(mapsingletype method)

I want to map my tables by columns to my model as I can't change the column names. I just want the newer version of that syntax in the blog.

Thank You.

like image 565
Manvendra Avatar asked Apr 09 '15 10:04

Manvendra


People also ask

How do I map a table in Entity Framework?

Map Entity to Table. Code-First will create the database tables with the name of DbSet properties in the context class, Students and Standards in this case. You can override this convention and give a different table name than the DbSet properties, as shown below.

What is DbContext in Entity Framework?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.


3 Answers

If you are using Code First, you can simply decorate your model with Table and Column attribute and give it the database names.

[Table("tbl_Student")]
public class Student
{
    [Column("u_id")]
    public int ID { get; set; }
}

These attributes are available in the System.ComponentModel.DataAnnotations.Schema namespace

like image 158
Praveen Paulose Avatar answered Sep 21 '22 09:09

Praveen Paulose


You can keep following inside OnModelCreating

modelBuilder.Entity<MyModel>()
.Property(e => e.MyColumn).HasColumnName("DBColumn")
like image 36
wonderbell Avatar answered Sep 21 '22 09:09

wonderbell


And if you're not using code-first, just select a table in the model diagram, hit F4 (properties) and change the name.

like image 43
simon at rcl Avatar answered Sep 20 '22 09:09

simon at rcl