Asp.net MVC 5数据库初始化程序不基于DateTime问题播种

时间:2015-05-13 08:55:55

标签: c# asp.net-mvc datetime asp.net-mvc-5 ef-code-first

非常感谢任何帮助

奇怪的是,结果正在数据库中记录,我使用的是代码优先方法,下面是一个模型示例:

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

namespace STRA.Models
{
    public class Category
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string CreatedBy { get; set; }
        //public Guid CreatedBy { get; set; }
        //var createdByEmail = User.Identity.GetUserName();
        //var createdById = User.Identity.GetUserId();
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
        public virtual ICollection<Question> Question { get; set; }
        public virtual ICollection<CategoryFeedback> CategoryFeedback { get; set; }
        public virtual ICollection<UserCategoryResult> UserCategoryResult { get; set; }
    }
}

以下是数据库初始化程序:

using IdentitySample.Models;
using System.Data.Entity;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using System.Collections;
using System.Collections.Generic;
using WebGrease.Css.Extensions;
using System;

namespace STRA.Models
{
    // This is useful if you do not want to tear down the database each time you run the application.
    // public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
    // This example shows you how to create a new database if the Model changes
    public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeIdentityForEF(context);
            base.Seed(context);
        }

        //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
        public static void InitializeIdentityForEF(ApplicationDbContext db)
        {
            # region Organisations creation

            IList<Organisation> organisations = new List<Organisation>();

            organisations.Add(new Organisation
            {
                Id = 1,
                Title = "White Springs",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            organisations.Add(new Organisation
            {
                Id = 2,
                Title = "Coles",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            organisations.Add(new Organisation
            {
                Id = 2,
                Title = "Holden",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            organisations.ForEach(o => db.Organisations.Add(o));
            //db.SaveChanges();

            # endregion



            # region Surveys Creation

            IList<Survey> surveys = new List<Survey>();

            surveys.Add(new Survey
            {
                Id = 1,
                Title = "STRA",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            surveys.Add(new Survey
            {
                Id = 2,
                Title = "Clientele Assessment",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            surveys.ForEach(s => db.Surveys.Add(s));
            //db.SaveChanges();

            # endregion

            # region Questions Creation

            IList<Question> questions = new List<Question>();

            questions.Add(new Question
                {
                    Id = 1,
                    SurveyId = 1,
                    CategoryId = 1,
                    Title = "I understand the value of the sales technology.",
                    DateCreated = DateTime.Now,
                    DateModified = DateTime.Now,
                });
            questions.Add(new Question
            {
                Id = 2,
                SurveyId = 1,
                CategoryId = 1,
                Title = "I am personally motivated to be part of the technology based change.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            questions.Add(new Question
            {
                Id = 3,
                SurveyId = 1,
                CategoryId = 1,
                Title = "I understand key business leaders support the change.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            questions.Add(new Question
            {
                Id = 4,
                SurveyId = 1,
                CategoryId = 1,
                Title = "I understand that driving sales technologies will impact my day-to-day work activities.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            questions.Add(new Question
            {
                Id = 5,
                SurveyId = 1,
                CategoryId = 1,
                Title = "I understand the risks of not changing the way we manage our sales technologies.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            questions.ForEach(q => db.Questions.Add(q));

            //db.SaveChanges();

            # endregion

            # region QuestionFeedback creation

            IList<QuestionFeedback> questionsFeedback = new List<QuestionFeedback>();

            questionsFeedback.Add(new QuestionFeedback
                {
                    Id = 1,
                    Rating = 1,
                    QuestionId = 1,
                    Feedback = "There is an intrinsic gap in understanding the value of technology, the value of its place in workflow and sales enablement. Gaps of this nature generally indicate a gap in communication. They also create a ripple affect on peers and teams. It is not ideal to implement any sales related technology with a vision of success when stakeholders only have a basic understanding.",
                    DateCreated = DateTime.Now,
                    DateModified = DateTime.Now,
                });
            questionsFeedback.Add(new QuestionFeedback
            {
                Id = 2,
                Rating = 2,
                QuestionId = 1,
                Feedback = "There is an intrinsic gap in understanding the value of technology, the value of its place in workflow and sales enablement. Gaps of this nature generally indicate a gap in communication. They also create a ripple affect on peers and teams. It is not ideal to implement any sales related technology with a vision of success when stakeholders only have a basic understanding.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            questionsFeedback.Add(new QuestionFeedback
            {
                Id = 3,
                Rating = 3,
                QuestionId = 1,
                Feedback = "There is a basic understanding of the sales technology but with room for improvement. Gaps of this nature generally indicate a gap in communication. They also create a ripple affect on peers and teams. It is not ideal to implement any sales related technology with a vision of success when stakeholders only have a basic understanding.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            questionsFeedback.Add(new QuestionFeedback
            {
                Id = 4,
                Rating = 4,
                QuestionId = 1,
                Feedback = "There is a clear understaning of the value your sales technology will create for the business. This is the ideal result and key to driving a ripple effect across your team.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            questionsFeedback.Add(new QuestionFeedback
            {
                Id = 5,
                Rating = 5,
                QuestionId = 1,
                Feedback = "There is a clear understaning of the value your sales technology will create for the business. This is the ideal result and key to driving a ripple effect across your team.",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            questionsFeedback.ForEach(qf => db.QuestionsFeedback.Add(qf));
            //db.SaveChanges();

            # endregion

            # region Categories creation

            IList<Category> categories = new List<Category>();

            categories.Add(new Category
            {
                Id = 1,
                Title = "Stakeholder Engagement",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            categories.Add(new Category
            {
                Id = 2,
                Title = "Communication",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            categories.Add(new Category
            {
                Id = 3,
                Title = "Alignment and Adaptibility",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            categories.Add(new Category
            {
                Id = 4,
                Title = "Performance Management",
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });
            categories.ForEach(c => db.Categories.Add(c));
            //db.SaveChanges();

            #endregion

            # region CategoryFeedback creation

            IList<CategoryFeedback> categoriesFeedback = new List<CategoryFeedback>();

            categoriesFeedback.Add(new CategoryFeedback
            {
                Id = 1,
                CategoryId = 1,
                FeedbackContent = "Stakeholder Engagement is defined as the process by which your organization involves people who are affected by or who influence the effect of change.Responsibility for managing change is with the senior leaders of the organization so any sales tech change must start with senior stakeholders and sales management engagement. This alignment cannot be taken for granted. It is imperative that work be done in advance to ensure that all stakeholders agree about the case for the sales tech change and the particulars for implementing it.Your score indicates a lower than average rating in relation to Stakeholder Engagement. This indicates little or limited engagement with senior leaders and/or the organisation. Where this is the case, the opportunity for a successful sales tech change is at risk. Where a technology is already in place, the risk of 'no change' around adoption and sustainability is immanent.It is not ideal to believe that your sales technology change will be successful when you are at this percentile. ",
                RangeType = "Low Range",
                AverageRating = 49,
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            categoriesFeedback.Add(new CategoryFeedback
            {
                Id = 2,
                CategoryId = 1,
                FeedbackContent = "Stakeholder Engagement is defined as the process by which your organization involves people who are affected by or who influence the effect of change.Responsibility for managing change is with the senior leaders of the organization so any sales tech change must start with senior stakeholders and sales management engagement. This alignment cannot be taken for granted. It is imperative that work be done in advance to ensure that all stakeholders agree about the case for the sales tech change and the particulars for implementing it.Your score indicates an average rating in Stakeholder Engagement. While this indicates there is some sponsorship and/or leadership engagement, it also indicates there is the potential to perform further diligence.Limted stakeholder engagement often occurs since managers are often required to engage with stakeholders who they may not report into. It also occurs when the sales tech change is not perceived as a priority by senior leaders/stakeholders.The resulting risk of limited stakeholder engagement is t the risk of 'no change' around adoption and sustainability and consequently no change in sales.",
                RangeType = "Mid Range",
                AverageRating = 50,
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            categoriesFeedback.Add(new CategoryFeedback
            {
                Id = 3,
                CategoryId = 1,
                FeedbackContent = "Stakeholder Engagement is defined as the process by which your organization involves people who are affected by or who influence the effect of change.Responsibility for managing change is with the senior leaders of the organization so any sales tech change must start with senior stakeholders and sales management engagement. This alignment cannot be taken for granted. It is imperative that work be done in advance to ensure that all stakeholders agree about the case for the sales tech change and the particulars for implementing it.Your score indicates a higher than average rating in Stakeholder Engagement. This is ideal when implementing any kind of sales tech change. Ensuring ongoing and active sponsorship in this way will allow you to drive your business and sales tech goals.",
                RangeType = "High Range",
                AverageRating = 70,
                DateCreated = DateTime.Now,
                DateModified = DateTime.Now,
            });

            categoriesFeedback.ForEach(cf => db.CategoriesFeedback.Add(cf));
            //db.SaveChanges();

            # endregion

            # region OrganisationSurvey Creation

            IList<OrganisationSurvey> organisationSurveys = new List<OrganisationSurvey>();

            organisationSurveys.Add(new OrganisationSurvey
                {
                    Id = 1,
                    OrganisationId = 1,
                    SurveyId = 1,
                });

            organisationSurveys.ForEach(os => db.OrganisationSurveys.Add(os));
            //db.SaveChanges();

            # endregion

            # region Admin creation
            var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            const string name = "admin@example.com";
            const string password = "Admin@123456";
            const string roleName = "Admin";
            const int organisation = 1;

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, OrganisationId = organisation };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
            //db.SaveChanges();
            #endregion

            # region Reports Creation

            IList<Report> reports = new List<Report>();

            reports.Add(new Report
            {
                ReportOutput = "Economic and technological change is driving an increasing need for organisations to adapt quickly and adeptly to sales market conditions. How companies manage their tech based sales changes and engage their workforce in the process can significantly impact their ability to achieve strategic business objectives.",
                User = user,
                SurveyId = 1,
            });

            reports.ForEach(r => db.Reports.Add(r));
            //db.SaveChanges();

            # endregion

            # region UserCategoryResult Creation

            IList<UserCategoryResult> userCategoriesResults = new List<UserCategoryResult>();

            userCategoriesResults.Add(new UserCategoryResult
            {
                UserAverageScore = 70,
                CategoryId = 1,
                User = user,
            });

            userCategoriesResults.Add(new UserCategoryResult
            {
                UserAverageScore = 80,
                CategoryId = 1,
                User = user,
            });

            userCategoriesResults.ForEach(ucr => db.UserCategoryResults.Add(ucr));
            //db.SaveChanges();

            # endregion

            # region UserQuestionResult Creation

            IList<UserQuestionResult> userQuestionResults = new List<UserQuestionResult>();

            userQuestionResults.Add(new UserQuestionResult
            {
                UserRating = 3,
                QuestionId = 1,
                User = user,
            });

            userQuestionResults.Add(new UserQuestionResult
            {
                UserRating = 5,
                QuestionId = 2,
                User = user,
            });

            userQuestionResults.ForEach(uqr => db.UserQuestionResults.Add(uqr));
            //db.SaveChanges();

            # endregion

            db.SaveChanges();
        }
    }
}

将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。 该语句已终止。   描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.Data.SqlClient.SqlException:将datetime2数据类型转换为datetime数据类型会导致超出范围的值。 声明已经终止。

来源错误:

Line 389:            # endregion
Line 390:
Line 391:            db.SaveChanges();
Line 392:        }
Line 393:    }

Models \ ApplicationDbInitializer.cs Line:391

2 个答案:

答案 0 :(得分:2)

此问题的根本原因是SQL Server和C#中日期时间类型的不同范围。 C#Datetime的最小值是1/1/0001 12:00:00 AM。如果SQL Server中的字段数据类型是datetime,则它将无法存储此值,因为SQL Server中支持的最小范围是01/01/1753 00:00:00

在sql server中将其更改为datetime2,问题将解决

我猜,在你的情况下,不知怎的。值由asp.net发送,可能是因为你没有为某些属性设置日期时间

答案 1 :(得分:0)

谢谢你们! 好的问题解决了!我发现有几种方法可以解决这个问题,包括使DataTypes可以为空,以及在每个类中创建一个多态方法:

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

namespace STRA.Models
{
    public class UserQuestionResult
    {
        public UserQuestionResult()
        {
            DateCreated = DateTime.Now;
            DateModified = DateTime.Now;
        }
        public int Id { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public int UserRating { get; set; }
        //navigation properties
        public virtual ApplicationUser User { get; set; }
        //public ICollection<ApplicationUser> ApplicationUser { get; set; }
        //public Guid ApplicationUserId { get; set; }
        //public ICollection<Report> Report { get; set; }
        public virtual Question Question { get; set; }
        public int QuestionId { get; set; }
    }
}