EF4 CTP5 Code First approach ignores Table attributes

坚强是说给别人听的谎言 提交于 2019-12-13 09:17:18

问题


I'm using EF4 CTP5 code first approach but am having trouble getting it to work. I have a class called "Company" and a database table called "CompanyTable". I want to map the Company class to the CompanyTable table, so have code like this:

[Table(Name = "CompanyTable")]
    public class Company
    {
        [Key]
        [Column(Name = "CompanyIdNumber", DbType = "int")]
        public int CompanyNumber { get; set; }

        [Column(Name = "CompanyName", DbType = "varchar")]
        public string CompanyName { get; set; }
    }

I then call it like so:

var db = new Users();
            var companies = (from c in db.Companies
                            select c).ToList();

However it errors out:

Invalid object name 'dbo.Companies'.

It's obviously not respecting the Table attribute on the class, even though it says here that Table attribute is supported. Also it's pluralizing the name it's searching for (Companies instead of Company.) How do I map the class to the table name?


回答1:


on you class that inherits from DbContext, override the OnModelCreating method

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Company>().ToTable("dbo.CompanyTable");
        }



回答2:


Forgot to add a reference to the ctp5 dll to my schemas project, it was using System.Data.Linq.Mapping instead.



来源:https://stackoverflow.com/questions/4493819/ef4-ctp5-code-first-approach-ignores-table-attributes

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