简体   繁体   中英

How do I add a RowVersion attribute to a EF4 class

I am using EF4 and creating classes through the Entity design surface then generating the database from them. I want to add an attribute to some of the classes to show the timestamp they were last updated.

I have added a Version attribute to them, but I don't know which .Net datatype to associate with them so they become either Timestamp or RowVersion in the database when it is generated.

Any ideas?

You use byte[] type for rowversion/timestamp

Example use: http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html

If you are in the designer, just type in byte[] or System.Byte[] , I think the field types dropdown selection on EF designer can be typed-in upon.

Given this DDL

create table Movie
(
MovieId int identity(1,1) not null primary key,
MovieName varchar(100) not null unique,
MovieDescription varchar(100) not null unique,
YearReleased int not null,
Version rowversion  -- rowversion and timestamp are alias of each other
);

This is the class mapping:

public class Movie
{
    [Key]
    public virtual int MovieId { get; set; }
     
    [   Required, Display(Name="Title")
    ]   public virtual string MovieName { get; set; }
     
    [   Required, Display(Name="Description")
    ]   public virtual string MovieDescription { get; set; }
     
    [   Required, Display(Name="Year Released"), Range(1900,9999)
    ]   public virtual int? YearReleased { get; set; }
     
    [Timestamp]
    // byte[] is the rowversion/timestamp .NET type
    public virtual byte[] Version { get; set; }  
 
     
    public virtual IList<Genre> Genres { get; set; }              
}

As far as I know, rowversion is a relative binary value, not an actual time value. It increments for every insert and update that occurs. This allows you to compare values to determine which record is newer. Since it is relative, given a single rowversion value, you will know nothing, but given two rowversion values, you will know which is older and which is newer, but not by how much.

I don't know which .Net datatype to associate with them so they become either Timestamp or RowVersion in the database when it is generated.

I'm not sure, but most likely there isn't a datatype that will give you rowversion when going from model to database. You will have to change the database field type yourself, or add the field to the DB and bring the record up to your model. You could also generate the DDL and then modify it before creating the DB with it.

There is also another method where you can extend the functionality of the EF process by deriving from it's classes. You can then choose it yourself, but I'm not too familiar with how to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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