【问题标题】:Saving a list of byte arrays (List<byte[]) with Entity Framework使用 Entity Framework 保存字节数组列表 (List<byte[])
【发布时间】:2019-01-20 19:04:45
【问题描述】:

我想使用 Entity Framework 保存位图图像列表。我读到我会将它们转换为字节数组,所以我做了相应的操作。

类如下所示:

public class ShootingLocation : LocationBase
{
    #region attributes
    public ParkingLocation ParkingLocation { get; set; }

    [MaxLength(16), Column(TypeName = "Binary")]
    public List<byte[]> LocationPhotos { get; set; }
    #endregion

    #region constructors
    public ShootingLocation()
    { 
    }
    #endregion
}

当我试图保存它的 DbContext 时,它会抛出异常。任何热门或替代解决方案?

【问题讨论】:

  • 您无法在数据库中保存任何内容的列表。您需要创建一个表并将它们放在那里
  • @CamiloTerevinto:不确定我是否理解正确:我是 Entity 框架的新手,但我的理解是框架会处理这个问题(创建适当的表和关系)......跨度>

标签: c# arrays list entity-framework


【解决方案1】:

如果要在每个拍摄位置存储多张照片,则需要在数据库中建立 1 对 n 关系,即,您必须有第二个相关的照片类/表

public class ShootingLocation : LocationBase
{
    public int ShootingLocationID { get; set; }

    public ParkingLocation ParkingLocation { get; set; }

    // Navigation property
    public ICollection<Photo> Photos { get; set; }
}

public class Photo
{
    public int PhotoID { get; set; }
    public string Description { get; set; }
    public byte[] ImageBytes { get; set; }

    // Navigation properties
    public int ShootingLocationID { get; set; }
    public ShootingLocation ShootingLocation { get; set; }
}

【讨论】:

  • @Oliver Jacot-Descombes:当然——但这应该是实体框架的一个功能——对吧?即使对于其他数据类型的多对多关系,这也是完美的——我认为它不起作用的原因是字节数组......
  • 没有。它不起作用的原因是字节数组列表。单独的字节数组有效。另一个实体类的列表也有效。因此,解决方案是为照片创建一个专用类,并为图像添加一个字节数组属性。然后,您可以将一组照片添加到拍摄地点。然后,ShootingLocationPhoto 必须作为数据集出现在 DbContext 中。
猜你喜欢
  • 2012-02-02
  • 2011-05-13
  • 2012-04-18
  • 2017-11-29
  • 1970-01-01
  • 2013-06-24
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多