【发布时间】:2017-04-01 01:22:17
【问题描述】:
我有一个图像模型:
public class Image
{
[Key]
public long ImagelId { get; set; }
public string base64 { get; set; }
}
我使用如下:
public class CoreGoal
{
[Key]
public long CoreGoalId { get; set; }
[Required]
public string Title { get; set; }
public virtual ICollection<Image> Images { get; set; }
public CoreGoal()
{
}
}
我正在使用 MySql 数据库。我打算针对每个 CoreGoal 将可能的多个图像存储为 base64 字符串。
每当我使用 base64 字符串发出 POST 请求时,它都是成功的,但是大部分字符串在保存到数据库时被截断。
我是否使用了错误的数据结构来存储 base64,即字符串?这是我的 ASP.Net 代码中的问题还是 MySql 的限制?
我该如何解决这个问题?
更新:
我的存储库类:
public class CoreGoalRepository : ICoreGoalRepository
{
private readonly WebAPIDataContext _db;
public CoreGoalRepository(WebAPIDataContext db)
{
_db = db;
}
//Add new
public void CreateCoreGoal(CoreGoal coreGoal)
{
_db.CoreGoals.Add(coreGoal);
_db.SaveChanges();
}
//Get all
public IEnumerable<CoreGoal> GetAllCoreGoals()
{
return _db.CoreGoals
.Include(coreGoal => coreGoal.Benefits)
.Include(coreGoal => coreGoal.Images)
.ToList();
}
}
public interface ICoreGoalRepository
{
void CreateCoreGoal(CoreGoal coreGoal);
IEnumerable<CoreGoal> GetAllCoreGoals();
}
我的控制器:
[Route("api/[controller]")]
public class CoreGoalController : Controller
{
private readonly ICoreGoalRepository _coreGoalRepository;
//Controller
public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
_coreGoalRepository = coreGoalRepository;
}
//Get methods
[HttpGet]
public IEnumerable<CoreGoal> GetAll()
{
return _coreGoalRepository.GetAllCoreGoals();
}
//Create
[HttpPost]
public IActionResult Create([FromBody] CoreGoal item)
{
if (item == null)
{
return BadRequest();
}
_coreGoalRepository.CreateCoreGoal(item);
return CreatedAtRoute("GetCoreGoal", new { id = item.CoreGoalId }, item);
}
}
【问题讨论】:
-
可能会被数据库截断。检查字符串的长度与数据库中字段的长度。
-
图像有多大,您要保存?它实际节省了多少?
-
ASP.NET Core 不会将任何内容保存到您的数据库中。这是其他一些技术,看起来您正在使用 EF 6 或 EF Core。来自 FluentMigrator 这样的迁移者?它是现有的数据库吗?在明确诊断之前需要回答这些问题。
-
由于您不确定是否使用您的数据模型,我建议您选择: 1. 如果您想坚持使用字符串,请将图像的路径引用存储在可通过以下方式访问的文件夹中重新定位您的 AspNet 应用程序。 2.在你的记录中使用BLOB字段,让mySql来处理。然后可以在后端或前端实现base64序列化/反序列化。如果你在谷歌上搜索你的问题,会有很多页面(以及这个问题的重复),也许你会发现更多的模式。
-
我会将它们保存为
byte[]和varbinary(max)
标签: asp.net-core asp.net-core-mvc entity-framework-core