不工作SaveChanges()方法ASP.NET MVC

时间:2016-07-23 20:13:22

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

我的代码运行时没有错误消息,但数据没有保存在数据库中。如何保存数据?

运行方法SavePictureToDatabase后,Visual 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; }
    }
}

ModelContext:

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>

数据库的结构:

2 个答案:

答案 0 :(得分:0)

你有任何例外吗?

如果您看到异常,则应编写以下代码。

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);
        }
    }
}

答案 1 :(得分:0)

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

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

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