Table name in data annotations in entity framework doesn't work.

asp.net-mvc data-annotations ef-code-first entity-framework-6

Question

I create a project in MVC 5 with entity framework 6. I am using code first approach. I want in one of the models define a different name for the table then the default. For that I use the System.ComponentModel.DataAnnotationsname space and define the class like this:

[Table(Name="Auditoria")]
public class AuditoriaDAL
{
    [Key]
    public int AuditoriaId { get; set; }

    ... 
}

Running the project I get a database with a table with the name AuditoriaDALs. Why the table have this name a not the name that I define?

1
0
8/25/2015 11:30:11 AM

Accepted Answer

You are referencing the System.Data.Linq.Mapping.Table attribute when you need to reference System.ComponentModel.DataAnnotations.Schema.Table. So either do this:

[System.ComponentModel.DataAnnotations.Schema.Table("Auditoria")]
public class AuditoriaDAL
{
    [Key]
    public int AuditoriaId { get; set; }

    ... 
}

Or better yet:

using System.ComponentModel.DataAnnotations.Schema;
...

[Table("Auditoria")]
public class AuditoriaDAL
{
    [Key]
    public int AuditoriaId { get; set; }

    ... 
}

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx

4
8/25/2015 2:38:05 PM

Popular Answer

you can set TableName like below :

public class MyContext : DBContext
{
  public virtual DbSet<AuditoriaDAL> Auditorias { get; set; }
}

Or in OnModelCreating :

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

        modelBuilder.Entity<AuditoriaDAL>().ToTable("Auditorias");
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow