将varchar转换为varbinary时出错,但我没有varbinary列

时间:2016-07-11 16:35:37

标签: c# sql-server entity-framework

我正在使用Visual Studio 2015,SQL Server 2014,EF 6,MVC 5. EF在varbinary(max)上向我抛出以下错误:

  

不允许从数据类型nvarchar到varbinary(max)的隐式转换。使用CONVERT函数运行此查询。

我无法弄清楚出了什么问题,因为我没有varchar;我从来没有。为什么要尝试在两者之间进行转换?如果它很重要,我尝试将列切换到MyContext,但同样的问题发生(错误中的varchar而不是nvarchar)。我该如何解决这个问题?

我通过将其放入Database.SetInitializer<NxContext>(null); 构造函数中来关闭迁移:

public class MyContext : DbContext
{
    public MyContext() : base("MyContext")
    {
        Database.SetInitializer<MyContext>(null);
    }

    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PersonMap());

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

EF背景:

public class Person
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

基类:

HasColumnType("nvarchar")

EF映射。我尝试使用public class PersonMap : EntityTypeConfiguration<Person> { public PersonMap() { Property(u => u.Email).IsRequired().HasMaxLength(320); Property(u => u.FirstName).IsRequired().HasMaxLength(75); Property(u => u.LastName).IsRequired().HasMaxLength(75); } } 指定列类型,但这没有效果。 (这是EF的默认值,所以它应该是不必要的。)

public class PersonService : IPersonService
{
    public void Create()
    {
        using (var db = new MyContext())
        {
            var person = new Person
            {
                Email = "test@example.com",
                FirstName = "TestFN",
                LastName = "TestLN"
            };
            db.Persons.Add(person);
            db.SaveChanges(); // error thrown here
        }
    }
}

更新数据库的简化方法:

{{1}}

数据库架构:

DB schema

1 个答案:

答案 0 :(得分:1)

在对评论进行一些争论之后,似乎问题是上下文没有获得正确的连接字符串,并且它在(localdb)上使用了不同的数据库,因此出现了奇怪的错误。

相关问题