此格式不支持数据类型“ varchar”

时间:2019-07-28 15:24:15

标签: entity-framework .net-core

我正在将具有现有数据库的旧项目转换为.Net core / EF core,并得到此异常。

System.ArgumentException: Data type 'varchar' is not supported in this form. Either specify the length explicitly in the type name, for example as 'varchar(16)', or remove the data type and use APIs such as HasMaxLength to allow EF choose the data type.

我在模型上使用了数据批注,但根据此答案EF core to support nvarchar切换到了丰富的api,但无法正常工作。

相关代码

CREATE TABLE [dbo].[Role] (
    [RoleId] INT           IDENTITY (1, 1) NOT NULL,
    [Name]   VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([RoleId] ASC),
    CONSTRAINT [RoleNameUnique] UNIQUE NONCLUSTERED ([Name] ASC),
    CONSTRAINT [UQ_Role_Name] UNIQUE NONCLUSTERED ([Name] ASC)
);

public class Role
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class EFContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_connString);
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Role>(entity =>
        {
            entity.Property(e => e.Name).IsRequired().HasColumnType("varchar(100)");
        });
    }           
}

// Throws error
var rv = Set<Role>();

0 个答案:

没有答案