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

笑着哭i 提交于 2019-12-21 07:55:24

问题


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.


回答1:


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




回答2:


You can keep following inside OnModelCreating

modelBuilder.Entity<MyModel>()
.Property(e => e.MyColumn).HasColumnName("DBColumn")



回答3:


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



来源:https://stackoverflow.com/questions/29536588/how-to-map-table-names-and-column-name-different-from-model-in-onmodelcreating-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!