简体   繁体   English

使用Code-First MVC5 EF6在SQL表中存储DateTime属性而不是字节数组

[英]Storing DateTime property instead of byte array in SQL table using Code-First MVC5 EF6

When I try to initialize my database using EF6 in MVC5 I get the error: The property 'Timestamp' is not a Byte array. 当我尝试在MVC5中使用EF6初始化我的数据库时,我得到错误: 属性'Timestamp'不是Byte数组。 IsRowVersion can only be configured for Byte array properties. IsRowVersion只能配置为字节数组属性。 Is there a way I can override the IsRowVersion using FluentAPI or is there another method to store DateTime using MVC5 EF6 or is this simply the result of using the Timestamp data annotation? 有没有办法可以使用FluentAPI覆盖IsRowVersion,或者是否存在使用MVC5 EF6存储DateTime的另一种方法,或者这只是使用Timestamp数据注释的结果? I prefer to store as DateTime instead of byte array. 我更喜欢将其存储为DateTime而不是字节数组。 Just for visualization Model looks like this: 仅用于可视化模型看起来像这样:

    public class UserProfile : IdentityUser
    {

        //ctor
        public UserProfile()
        {
            Random rnd = new Random();
            int pic = rnd.Next(1, 6); 

            DateJoined = DateTime.Now;
            UserLevel = 4;
            ImageUrl = "/Content/Avatars/Samples/sample" + pic + ".jpg"; // or append .jpg which == .jpg
        }

        public UserProfile(string name, string url)
        {
            UserName = name;
            DateJoined = DateTime.Now;
            UserLevel = 4;
            ImageUrl = url;
            Email = "your@email.com";
        }

        public UserProfile(string name, string url, string email)
        {
            Random rnd = new Random();
            int pic = rnd.Next(1, 6);
            UserName = name;
            DateJoined = DateTime.Now;
            UserLevel = 4;
            ImageUrl = "/Content/Avatars/sample" + pic + ".jpg"; // or append .jpg which == .jpg
            Email = email;
        }
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        [Required(ErrorMessage="*Username is required."), RegularExpression(@"^[\p{L} \p{Nd}_]+$")]
         [MinLengthAttribute(5, ErrorMessage="Not enough characters! UserName must be at least 5 chars."), MaxLengthAttribute(30,ErrorMessage="Too many characters in UserName!")]
        public override string UserName { get; set; }
        [Required(ErrorMessage="*Email is required."), EmailAddress, RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { get; set; }
        [ScaffoldColumn(false),Required]
        public string ImageUrl { get; set; }
        [DisplayFormat(DataFormatString = "{0}")] //{0:d} or {0:D}
        [DataType(DataType.DateTime), Timestamp, ScaffoldColumn(false)] //<--Problem 
        public DateTime DateJoined { get; set; }
        [Range(1, 6), ScaffoldColumn(false)]
        public int UserLevel { get; set; }
        [ScaffoldColumn(false)]
        public int? TotalRepPoints { get; set; }
        [ScaffoldColumn(false)]
        public virtual IDictionary<int, int> TotalPointsByCat { get; set; }
        // int = CategoryId, int = UserRank
        public virtual IDictionary<int, int> Rankings { get; set; }
        public virtual ICollection<Article> Articles { get; set; }
        public virtual ICollection<Answer> Answers { get; set; }
        public virtual ICollection<Vote> Votes { get; set; }
        public virtual ICollection<Question> Questions { get; set; }

    }

When I use NuGet Console: 当我使用NuGet控制台时:

 PM> Enable-Migrations -Force
Checking if the context targets an existing database...
System.InvalidOperationException: The property 'Timestamp' is not a Byte array. IsRowVersion can only be configured for Byte array properties.
   at System.Data.Entity.ModelConfiguration.Configuration.ConventionPrimitivePropertyConfiguration.IsRowVersion()
   at System.Data.Entity.ModelConfiguration.Conventions.TimestampAttributeConvention.Apply(ConventionPrimitivePropertyConfiguration configuration, TimestampAttribute attribute)
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
...
    The property 'Timestamp' is not a Byte array. IsRowVersion can only be configured for Byte array properties.
    PM> 

Thanks in advance! 提前致谢!


EDIT 编辑

When storing properties using data annotation [DataType(DataType.DateTime)] with DateTime? 使用DateTime?使用数据注释[DataType(DataType.DateTime)]存储属性时DateTime? class you will get datetime type field in SQL. 您将在SQL中获取日期时间类型字段。

When storing properties using data annotation [Timestamp] with byte[] you will get timestamp type field in SQL. 使用带有byte[]数据注释[Timestamp]存储属性[Timestamp] ,您将在SQL中获得时间戳类型字段。

在此输入图像描述

From the Microsoft documentation on timestamp (AKA rowversion ) (emphasis added): 关于timestampMicrosoft文档(AKA rowversion (重点补充):

Is a data type that exposes automatically generated, unique binary numbers within a database. 是一种在数据库中公开自动生成的唯一二进制数的数据类型。 rowversion is generally used as a mechanism for version-stamping table rows. rowversion通常用作版本标记表行的机制。 The storage size is 8 bytes. 存储大小为8个字节。 The rowversion data type is just an incrementing number and does not preserve a date or a time. rowversion数据类型只是一个递增的数字,不保留日期或时间。 To record a date or time, use a datetime2 data type. 要记录日期或时间,请使用datetime2数据类型。

So this data type, despite its old name, has essentially nothing to do with actual datetime values as we generally think of them. 所以这个数据类型,尽管它的旧名称,基本上与我们通常认为的实际日期时间值无关。

Pick another column type, like datetime. 选择其他列类型,例如datetime。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM