【问题标题】:Not working SaveChanges() method ASP.NET MVC不工作 SaveChanges() 方法 ASP.NET MVC
【发布时间】:2016-07-26 05:46:53
【问题描述】:

我的代码运行时没有错误消息,但数据未保存在数据库中。我该怎么做才能让它保存数据?

运行方法SavePictureToDatabaseVisual Studio 后显示此信息:

我的模特:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace userGallery.Models
{
    public class Image
    {
        public int Id { get; set; }
        public int AccountId { get; set; }
        public string Name { get; set; }
    }
}

模型上下文:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace userGallery.Models
{
    public class ImageContext : DbContext
    {
        public DbSet<Image> Images { get; set; }
    }
}

控制器:

public class UserController : Controller
    {
        ImageContext context = new ImageContext();

        // GET: User
        public ActionResult Download()
        {
            return View();
        }

        public string SavePictureToDatabase()
        {    
            Image image = new Image()
            {
                AccountId = 1,
                Name = "123",
            };

            context.Images.Add(image);
            context.SaveChanges();

            return urlPicture;
        }

连接字符串:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-userGallery-20160714070926.mdf;Initial Catalog=aspnet-userGallery-20160714070926;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

数据库结构:

【问题讨论】:

  • 你有连接字符串吗?
  • 已添加连接字符串
  • 请写下异常堆栈跟踪。

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

当 DbContext 类名和 ConnectionString 不相等时,将 connectionString 传递给 DbContext

public class ImageContext : DbContext
{
    public ImageContext (): base("DefaultConnection")
    {
    }

    public DbSet<Image> Images { get; set; }
} 

【讨论】:

    【解决方案2】:

    你有什么例外吗?

    如果你看到异常,你应该写下面的代码。

    try 
    {
        Context.Content.Add(content);
        Context.SaveChanges();
    }
    catch (DbEntityValidationException e) 
    {
        foreach(var eve in e.EntityValidationErrors) 
        {
            Console.WriteLine("Entity  \"{0}\" exceptions \"{1}\" :", eve.Entry.Entity.GetType().Name, eve.Entry.State);
            foreach(var ve in eve.ValidationErrors) 
            {
                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多