Search code examples
entity-frameworkannotationsef-code-firstcode-first

Entity Framework Code First Data Annotation MaxLength and Table Not Working


I'm using Code First approach to create my data base from my model and I used data annotations in my class like this:

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

[Table("Cat1")]
public class Cat
{
    public int ID { get; set; }
    [Required]
    [MaxLength(50)]
    public string Nombre { get; set; }
    [StringLength(500)]
    public string Descripción { get; set; }
}

using System.Data.Entity;
public class Contexto: DbContext  {
    public DbSet<Cat> Cats { get; set; }
    protected override void OnModelCreating(DbModelBuilder MB) {
        MB.Conventions.Remove<PluralizingTableNameConvention>();
        MB.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        MB.Conventions.Remove<ForeignKeyIndexConvention>();
        MB.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        MB.ComplexType<Departamento>(); 
        MB.ComplexType<Porción>();
    }
}

But for some reason only the [Required] and [StringLength] annotations get applied. My database ends like this:

TABLE [dbo].[Cats] (
    [ID]          INT            IDENTITY (1, 1) NOT NULL,
    [Nombre]      NVARCHAR (MAX) NOT NULL,
    [Descripción] NVARCHAR (500) NULL,
    CONSTRAINT [PK_dbo.Cats] PRIMARY KEY CLUSTERED ([ID] ASC)
);

I'm wondering why some annotations are working and others don't. I know I can use 'StringLength' instead of 'MaxLength', but I don't have other option for 'Table' and some others that may have the same problem. It used to work fine for a while but then suddenly stopped working. How can I make 'MaxLenght' and 'Table' annotations work again? Edit: Other annotations not working: ComplexType and NotMapped.

I'm using EF 6.1.3 and targetframework net40 and Visual Studio 2017.

Thank you!


Solution

  • So after many many hours I decided to start the whole project from scratch. The only thing that I made different this time was to specify the .Net Framework 4.0 at the start of each project, before adding any reference or NuGet package. I think that last time I was manually moving a lot of stuff that ended up confusing visual studio, for intellisense it was fine Table, ComplexType and NotMaped annotations but in reality there weren't applied.