SaveChanges 不适用于我的所有项目?

SaveChanges is not working in all my project?

我使用 Visual StudioASP.NET MVC 项目上使用本地数据库。

我在修改数据库时遇到问题。当我调用 SaveChanges() 时,我总是得到这个错误:

The value cannot be null Parameter Name: Source

这是我如何修改数据库的示例,以及错误日志/StackTrace。

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateMedico(Medico medicoToCreate)
    {
        List<Medico> dedo = data.Medico.ToList();
        if (ModelState.IsValid)
        {
            using (MedsEntities data = new MedsEntities())
            {
                medicoToCreate.Id = dedo.Count() + 1;
                data.Medico.Add(medicoToCreate);
  System.Diagnostics.Debug.WriteLine("RECURSO :" + medicoToCreate.RECURSO_MEDICO);
                    System.Diagnostics.Debug.WriteLine("NOMBRE: " + medicoToCreate.NOMBRE);
                    System.Diagnostics.Debug.WriteLine("TIPO: " + medicoToCreate.TIPO);
                // and so on with all properties.....
                System.Diagnostics.Debug.WriteLine("MEDICO A GRABAR:" + medicoToCreate.NOMBRE);
                if (medicoToCreate == null)
                {
                    System.Diagnostics.Debug.WriteLine("MEDICOTOCREATE, IS NULL");

                }
                else {
                    System.Diagnostics.Debug.WriteLine("MEDICOTOCREATE, IS NOT NULL");
                }
                data.SaveChanges();
                return RedirectToAction("MedicosList");
            }
        }

        return RedirectToAction("MedicosList");
    }

堆栈跟踪:

   en System.Data.Entity.Internal.InternalContext.SaveChanges()
   en System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   en System.Data.Entity.DbContext.SaveChanges()
   en FINAL.Controllers.HomeController.CreateMedico(Medico medicoToCreate) en d:\IDEX8544 KARLO\Documents\Visual Studio 2012\Projects\FINAL\FINAL\Controllers\HomeController.cs:línea 70
   en lambda_method(Closure , ControllerBase , Object[] )
   en System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   en System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   en System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   en System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   en System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   en System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   en System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   en System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   en System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49(

连接字符串(感谢 Oleg):

 <connectionStrings>
    <add name="MedsEntities" connectionString="metadata=res://*/Models.ModelMeds.csdl|res://*/Models.ModelMeds.ssdl|res://*/Models.ModelMeds.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\DB.sdf&quot;" providerName="System.Data.EntityClient" />
    <add name="HospitalEntities" connectionString="metadata=res://*/Models.ModelHosp.csdl|res://*/Models.ModelHosp.ssdl|res://*/Models.ModelHosp.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\DB.sdf&quot;" providerName="System.Data.EntityClient" />
    <add name="LabsEntities" connectionString="metadata=res://*/Models.ModelLabs.csdl|res://*/Models.ModelLabs.ssdl|res://*/Models.ModelLabs.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\DB.sdf&quot;" providerName="System.Data.EntityClient" />
    <add name="FarmaciasEntities" connectionString="metadata=res://*/Models.ModelFarms.csdl|res://*/Models.ModelFarms.ssdl|res://*/Models.ModelFarms.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\DB.sdf&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

医学模型:

namespace FINAL.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Medico
    {
        public string RECURSO_MEDICO { get; set; }
        public string NOMBRE { get; set; }
        public string TIPO { get; set; }
        public string TIPO2 { get; set; }
        public string TIPO3 { get; set; }
        public string CELULAR { get; set; }
        public string EMAIL { get; set; }
        public string TEL1 { get; set; }
        public string TEL2 { get; set; }
        public string EXT { get; set; }
        public string HOSPITAL { get; set; }
        public string DIRECCION { get; set; }
        public string LAT { get; set; }
        public string LON { get; set; }
        public string C33DIGITOS { get; set; }
        [Key]
        public int Id { get; set; }
    }
}

数据库模型:

namespace FINAL.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MedsEntities : DbContext
    {
        public MedsEntities()
            : base("name=MedsEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Medico> Medico { get; set; }
    }
}

有多种问题会导致 EF 中出现此错误消息。

据我所知,Entity Framework 依赖于您的对象具有一些唯一标识符。 拥有一个的最简单方法是您拥有的 Id,但您不应将其设置为可为空。它应该是 int 类型,并且您的 SQL 服务器应该将此列的标识设置为 true。

如果这不是您的问题,请在调用 SaveChanges 之前调试并检查设置了哪些值,更重要的是哪些值仍然为空。

您收到此异常是因为您的某些 Model 属性 具有 null 值。但是在检查这个之前,我建议你在你的模型中创建一个 key 列,它不应该是 Nullable。当你添加一个新的 object 你的 model 值时 key 列应该在调用 SaveChanges.

之前设置

你的关键列应该是这样的

[Key]
public int Id { get; set; }

如果您不想在添加新的 object 时手动设置此 key 列的值,您可以将其设置为标识列,这样它的值将自动插入将 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 添加到您的 key 列。

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

并确保在添加新的 object 时所有属性都具有该值,否则您将得到相同的异常。

如果删除 Bind(Exclude = "Id") 属性是否有效?

这似乎是罪魁祸首。看起来您是在 DomainModel 而不是 ViewModel 上使用它。您试图在事后设置它,但该属性已经设置。

有几种解决方法。

  • 创建一个仅包含您希望可编辑的属性的 ViewModel,然后将其传回并映射到您的 DomainModel。

  • 让你的数据库处理自动增量

  • 只需删除 Bind(Exclude = "Id") 属性,不要公开 属性(如上)

您最终试图在没有标识符的情况下插入。

您可以在此处查看此答案,其中包含更多详细信息:Alternative for [Bind(Exclude = “Id”)]