试图在种子方法中的 SaveChanges 中找出我的验证错误

Mic*_*nor 3 c# database validation nuget-package entity-framework-6

我试图找出在我更新数据库时导致验证异常的具体验证错误是什么。我有理由确信罪魁祸首是SaveChanges(). 我认为我的 3 个类中的一个或多个中的一个或多个属性有问题。解决异常的唯一方法是发现验证错误。

尽管我对几种不同的语言有经验,但在这种调试方式方面,我还是个新手。我在指示的地方设置了一个断点,所以我可以看到debug.writeline结果,但有两个问题:它永远不会在断点处停止,而且我在输出窗口下拉列表中没有看到“调试”。

我不明白什么?有没有更好的方法来捕获验证错误?

这是 configuration.cs 文件中的完整代码。

namespace AlbumSong2.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Validation;
    using System.Diagnostics;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<AlbumSong2.Model.AlbumDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            //if (System.Diagnostics.Debugger.IsAttached == false)
            //    System.Diagnostics.Debugger.Launch();
        }

        protected override void Seed(AlbumSong2.Model.AlbumDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            context.Singers.AddOrUpdate(t => t.SingerName,
                new Singer() { SingerName = "Chuck Negron" },
                new Singer() { SingerName = "Cory Wells" },
                new Singer() { SingerName = "Dan Hutton" });
            context.SaveChanges();

            try
            {
                context.Albums.AddOrUpdate(t => t.AlbumName,
                    new Album()
                    {
                        AlbumName = "Three Dog Night",
                        AlbumTitle = "Seven Separate Fools",
                        Price = 15,
                        aLength = 45,
                        Year = "1972",
                        isUSA = true,
                        CurrentSingerId = 1
                    },
                    new Album()
                    {
                        AlbumName = "Steppenwolf",
                        AlbumTitle = "Cyan",
                        Price = 10,
                        aLength = 35,
                        Year = "1973",
                        isUSA = true,
                        CurrentSingerId = 2
                    },
                    new Album()
                    {
                        AlbumName = "Grand Funk Railroad",
                        AlbumTitle = "It Ain't Easy",
                        Price = 10,
                        aLength = 35,
                        Year = "1970",
                        isUSA = true,
                        CurrentSingerId = 3
                    });
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Debug.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                            ve.PropertyName, 
                            eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
                            ve.ErrorMessage);
                    }
                }
                throw;
            }

            try
            { 
            context.Songs.AddOrUpdate(t => t.SongTitle,
                new Song() { SongTitle = "Black and White", sLength = 4, CurrentAlbumId = 1 },
                new Song() { SongTitle = "Let Me Seranade You", sLength = 3, CurrentAlbumId = 2 },
                new Song() { SongTitle = "Mama Told Me (Not To Come)", sLength = 3, CurrentAlbumId = 3 });
            context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Debug.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                            ve.PropertyName,
                            eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName), 
                            ve.ErrorMessage);
                    }
                }
                throw;
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

专辑类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AlbumSong2
{
    //[Table("Albums")]
    public class Album
    {
        public int AlbumId { get; set; }
        [MinLength(5), MaxLength(25), Required]
        public string AlbumName { get; set; }
        [MinLength(5), MaxLength(25), Required]
        public string AlbumTitle { get; set; }
        public string Year { get; set; }
        [Range(10, 50)]
        public int aLength { get; set; }
        [Range(1, 15)]
        public double Price { get; set; }
        public bool isUSA { get; set; }

        //navigation property -> each Album has many Songs, indicating dependent (child) entity
        public List<Song> Songs { get; set; }

        //navigation property -> indicates parent table
        public Singer CurrentSinger { get; set; }

        [ForeignKey("CurrentSinger")]
        public int? CurrentSingerId { get; set; }


    }
}
Run Code Online (Sandbox Code Playgroud)

和歌曲类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


namespace AlbumSong2
{
    //[Table("Songs")]
    public class Song
    {
        public int SongId { get; set; }

        [MinLength(2), MaxLength(45)]
        [Required]
        public string SongTitle { get; set; }
        public int sLength { get; set; }

        //navigation property -> indicates parent table
        public Album CurrentAlbum { get; set; }

        [ForeignKey("CurrentAlbum")]
        public int CurrentAlbumId { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后是歌手课。(数据库或代码中的singer表没有任何问题。另外两个我有问题):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AlbumSong2
{
    //[Table("Singers")]
    public class Singer
    {
        public int SingerId { get; set; }

        [MinLength(5), MaxLength(25)]
        [Required]
        public string SingerName { get; set; }

        //navigation property -> each Singer has many Albums
        public List<Album> Albums { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 VS 程序的屏幕截图,显示了断点和验证错误。

VS截图

Mic*_*nor 5

我已将 try/catch 例程从配置文件移动到 AlbumDbContext,在那里我能够成功捕获错误。这是 AlbumDbContext 文件中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Text;
using System.Runtime.Remoting.Contexts;

namespace AlbumSong2.Model
{
    public class AlbumDbContext : DbContext
    {
        public AlbumDbContext() : base("AlbumDbConnection2") { }
        public IDbSet<Singer> Singers { get; set; }
        public IDbSet<Album> Albums { get; set; }
        public IDbSet<Song> Songs { get; set; }


        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是输出!

在此处输入图片说明

问题解决了。