You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Entity Framework C# Code First中设置varbinary最大值

解决Code First中byte[]字段生成varbinary(max)的问题

你的问题核心原因是:fotografia字段被EF Code First自动设置为主键(PK),而SQL Server中主键的默认最大长度限制为900字节,因此生成的字段类型是varbinary(900),而非预期的varbinary(max)。

以下是两种可行的解决方案:

方案一:使用数据注解配置

修改POCO类,添加独立主键字段,并通过注解强制指定fotografia字段类型为varbinary(max):

public class Fotografia
{
    // 添加独立主键字段,避免byte[]被自动设为主键
    public int Id { get; set; }

    [Display(Name = "Fotografía")]
    [Column(TypeName = "varbinary(max)")]
    public required byte[] fotografia { get; set; }
}

方案二:使用Fluent API配置

如果偏好通过DbContext配置实体,可在OnModelCreating方法中进行设置:
首先修改POCO类添加主键字段:

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

    [Display(Name = "Fotografía")]
    public required byte[] fotografia { get; set; }
}

然后在DbContext中配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // 指定Id为实体主键
    modelBuilder.Entity<Fotografia>().HasKey(f => f.Id);

    // 设置fotografia字段类型为varbinary(max)并标记为必填
    modelBuilder.Entity<Fotografia>()
        .Property(f => f.fotografia)
        .HasColumnType("varbinary(max)")
        .IsRequired();
}

注意:若你确实需要将byte[]字段作为主键,SQL Server不允许主键长度超过900字节,这种场景下建议改用其他类型(如int、Guid)作为主键,将byte[]作为普通字段存储。

内容的提问来源于stack exchange,提问作者LuisDSS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:46:03