带有身份的ASP.NET:实体框架在SaveChanges上引发System.Data.Entity.Core.UpdateException

时间:2018-07-28 18:06:47

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

我正在尝试构建一个应该便于拼车的ASP.NET应用程序。 为此,我使用身份框架将帐户和实体框架作为ORM进行管理。我也为模型使用了Identity的ApplicationDbContext,因此我不会在代码优先迁移方面遇到问题,因为我需要UserProfile对象与Identity的ApplicationUser之间是一对一的关系。

这是我的模特:

public class UserProfile
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }

        public virtual List<Trip> Trips { get; set; } = new List<Trip>();
        public virtual List<Meeting> Meetings { get; set; } = new List<Meeting>();
    }

public class Trip
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public virtual TripCheckpoint Departure { get; set; }
    [Required]
    public virtual TripCheckpoint Destination { get; set; }
    [Required]
    public int Seats { get; set; }
    [NotMapped]
    public int AvailableSeats => Seats - Passengers.Count;
    [Required]
    public virtual UserProfile Organizer { get; set; }
    public double Price { get; set; } = 0.0;
    public virtual List<UserProfile> Passengers { get; } = new List<UserProfile>();
    public virtual DateTime Date { get; set; }
}

public class TripCheckpoint
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CheckPointId { get; set; }
    [Required]
    public string Place { get; set; }
    [Required]
    public TimeSpan Hour { get; set; }
}

public class Meeting
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime When { get; set; }
    public string Where { get; set; }
}

这是我的ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<UserProfile> Profiles { get; set; }
    public DbSet<Trip> Trips { get; set; }
    public DbSet<TripCheckpoint> Checkpoints { get; set; }
    public DbSet<Meeting> Meetings { get; set; }

    public ApplicationDbContext()
        : base("helmoCars", throwIfV1Schema:false)
    {

    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder dbBuilder)
    {
        base.OnModelCreating(dbBuilder);
        dbBuilder.Entity<ApplicationUser>().HasRequired(u => u.Profile).WithRequiredPrincipal().Map(m => m.MapKey("AppUser_Id"));
        dbBuilder.Entity<Trip>().HasMany(t => t.Passengers).WithMany().Map(m =>
        {
            m.ToTable("Trip_Passengers");
            m.MapLeftKey("Trip_Id");
            m.MapRightKey("UserProfile_Id");
        });
        dbBuilder.Entity<Trip>().HasRequired(t => t.Organizer).WithMany(u => u.Trips).Map(m => m.MapKey("Trip_Organizer"))
            .WillCascadeOnDelete(false);
        dbBuilder.Entity<Trip>().HasRequired(t => t.Departure).WithRequiredDependent().Map(m => m.MapKey("Trip_Departure")).WillCascadeOnDelete(false);
        dbBuilder.Entity<Trip>().HasRequired(t => t.Destination).WithRequiredDependent().Map(m => m.MapKey("Trip_Destination")).WillCascadeOnDelete(false);

    }
}

这是我使用ApplicationDbContext的方式:

public class TripRepository
{
    private ApplicationDbContext _db;

    public TripRepository(ApplicationDbContext context)
    {
        this._db = context;
    }

    public void AddTrips(List<Trip> trips)
    {
        _db.Database.Log = message => Debug.Write(message);
        _db.Trips.AddRange(trips);
        _db.SaveChanges();
    }
}

我这样使用TripRepository:

ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
var tr = new TripRepository(context);
tr.AddTrips(trips); // trips is a valid List<Trip>

ApplicationDbContext的SaveChanges()方法每次调用时都会引发System.Data.Entity.Core.UpdateException,即使我确定添加到DbSet的行程是有效的列表,也已对其进行了检查与调试器。 唯一的例外是我收到的反馈,所以我真的不知道自己在做什么错。有什么想法吗?

这是我在调试输出窗口中得到的唯一反馈:

Exception levée : 'System.Data.Entity.Core.UpdateException' dans 
EntityFramework.dll
Exception levée : 'System.Data.Entity.Core.UpdateException' dans 
EntityFramework.SqlServer.dll
Exception levée : 'System.Data.Entity.Infrastructure.DbUpdateException' dans 
EntityFramework.dll
Exception levée : 'System.Data.Entity.Infrastructure.DbUpdateException' dans 
System.Web.Mvc.dll
Exception levée : 'System.Data.Entity.Infrastructure.DbUpdateException' dans 
System.Web.Mvc.dll

这是我填写之后提供给AddTrips方法的列表的方式(其中trip是从表单获得的viewmodel):

trips.Add(new Trip()
                {
                    Date = trip.Date,
                    Price = trip.Price,
                    Seats = trip.Seats,
                    Organizer = user,
                    Departure = new TripCheckpoint() { Place = trip.DeparturePlace, Hour = trip.DepartureHour.TimeOfDay },
                    Destination = new TripCheckpoint() { Place = trip.DestinationPlace, Hour = trip.DestinationHour.TimeOfDay }
                });

1 个答案:

答案 0 :(得分:0)

我在视图中发现了更好的日志(我正在使用AJAX)。对于其他有问题的人,如果希望更好的日志查找错误,请尝试使用html表单将其尝试,并在工作后将其转换为ajax表单。