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

ef-migrations entity-framework-core maxlength sql-server varchar


I have the following:

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..

8/27/2015 3:14:31 PM

Accepted Answer

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

            .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.


8/27/2015 3:51:06 PM

Popular Answer

OK using .net core 2 targeting sql server I had this issue. My model builder looked like this.

            .Property(e => e.StreamName)

Once I removed the HasColumnType and let it choose varchar automatically based on my StreamCheckpointDto.StreamName being a string the length became 40 as expected. you might also be able to use.



Related Questions


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