首页 > 解决方案 > 在实体框架模型中将数据插入 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)

标签: .netsql-serverentity-framework

解决方案


请使用 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;
}

推荐阅读