Entity Framework 7 migration: how to get a varchar column with a length greater than 1?

code-first-migrations entity-framework-core maxlength sql-server varchar

Question

I have the following:

[Table("Countries")]
public class Country
{
    public int CountryId { get; set; }

    [MaxLength(255), Required]
    public string CountryName { get; set; }

    [Column(TypeName = "varchar")]
    public string CountryCode { get; set; }
}

Every time I apply my migration, CountryCode becomes a varchar column with a max length of 1. I tried setting the MaxLength annotation to 255 and still get a max length of 1. When the column is set as nvarchar it works as expected. Am I doing something wrong?

Edit: Whenever I explicitly set the string data type, length sets to 1. I could have used Column(TypeName = "nvarchar")] and the length sets as 1..

Accepted Answer

Would of liked to have used data annotations, but I was able to get it to work with:

 builder.Entity<Country>()
            .Property(e = e.CountryCode).HasSqlServerColumnType("VARCHAR(30)");

Data Annotations are not yet fully implemented in Entity Framework 7. You can still add annotations to your entity classes so that they are used by other frameworks (such as ASP.NET MVC), but Entity Framework will not process these annotations. You can track support for Data Annotations on GitHub.

http://ef.readthedocs.org/en/latest/modeling/configuring.html



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why