.net - 在实体框架模型中将数据插入 SQL Server
问题描述
我的代码只列出了数据库目前拥有的内容,但我需要将数据插入其中。
namespace WebApplication5.Controllers
{
public class DefaultController : ApiController
{
public IEnumerable<Table_1> Get()
{
using (testEntities entities = new testEntities())
{
Table_1 us = new Table_1() { id = "221", name = "asdsadasdsad" };
entities.Table_1.Add(us);
entities.SaveChangesAsync();
return entities.Table_1.ToList();
}
}
}
}
通常 db 使用该查询进行更新
Insert into Table_1 values ('111','222')
id (string)
name(string)
解决方案
请使用 try-catch 块并找到导致上述错误的验证错误。
try
{
using (testEntities entities = new testEntities())
{
using (testEntities entities = new testEntities())
{
Table_1 us = new Table_1() { id = "221", name = "asdsadasdsad" };
entities.Table_1.Add(us);
entities.SaveChangesAsync();
return entities.Table_1.ToList();
}
}
}
catch (DbEntityValidationException ex)
{
foreach (var ve in ex.EntityValidationErrors)
{
foreach (var err in ve.ValidationErrors)
{
Console.WriteLine("Property Name: \"{0}\", Error Message: \"{1}\"", err.PropertyName, err.ErrorMessage);
}
}
throw;
}
推荐阅读
- python - 收集错误报告?
- java - java创建带有发送模式的对象的文件名
- mysql - mysql如果选择是我的ID不返回任何行
- python-3.x - 如何在另一个函数中读取的函数中重新打开文件?
- java - java - 如何在创建Java Spring MVC时将大量数据作为文件提供?
- javascript - 将 JSON 数据解析为 C3.js 图表的数组
- javascript - 如何在页面中添加 HTML 模板?
- python - 在巨大的文本文件目录 python/bash 中搜索大量条目
- angular - NgModule,@NgModule,AppModule
- html - 如何将引导程序 scss 编译为 css