Error storing Image in SQL CE 4.0 with ASP.NET MVC 3 and Entity Framework 4.1 Code First

安稳与你 提交于 2019-11-29 05:37:21

For those experiencing this problem, Erik Ejlskov Jensen posted a working console application which demonstrates the workaround to this bug. As the OP noted, a key part of the answer is:

    public StudentContext()
    {
        // Required to prevent bug - http://stackoverflow.com/questions/5737733
        this.Configuration.ValidateOnSaveEnabled = false;        
    }

A better solution has been found. Do not disable validation. [Updates from blog post] UPDATE: @DamienGuard, of LINQ to SQL and EF Code First fame, pointed out that a better and more provider agnostic solution is to use MaxLength rather than TypeName = “ntext”.

UPDATE 2: Using [MaxLength] prevents any validation errors, and disabling validation is not required.

The way to specify no maximum length using the MaxLength data annotation is to provide no maximum value. For example:

[MaxLength]
public byte[] Photo { get; set; }

The SQL Compact provider will then map the property to "image" and EF validation will recognize that there is no max length specified and so does not need to be disabled. If you want to be explicit about mapping to an "image" column then you can do this:

[Column(TypeName = "image")]
[MaxLength]
public byte[] Photo { get; set; }

which will produce the same result when using SQL Compact.

I know this is too late, but it could benefit other programmers.

You could add to the context class inside the OnModelCreating(DbModelBuilder modelBuilder) method

 modelBuilder.Entity<EntityName>().Property(p => p.Photo).IsMaxLength();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!