简体   繁体   English

如何将SQL时间戳转换为实体框架中的字符串?

[英]How to convert SQL timestamp to a string in Entity Framework?

I need to retrieve the MAX(timestamp) value from a SQL table into a string variable but can't figure out how. 我需要从SQL表中检索MAX(时间戳)值到字符串变量,但无法弄清楚如何。

So if my table/entity is set up like so: 所以,如果我的表/实体设置如下:

**DEPARTMENTS**
Department  varchar(10) PK
LastUpdated timestamp

What would the Linq query look like? Linq查询会是什么样子? I have tried a few iterations but always get an error. 我尝试了几次迭代但总是出错。

EDIT: Here is an example of what I tried 编辑:这是我尝试的一个例子

 var result = (from d in _context.LOG_Departments
                      select d.LastUpdated).Max().SingleOrDefault();

error: "Cannot implicitly convert type 'byte' to 'string' 错误:“无法将类型'byte'隐式转换为'string'

EDIT Solution: 编辑解决方案:

public string MaxDepartment()
    {

        CPLinkEntities _context = new CPLinkEntities();
        var results = _context.LOG_Departments.Max(t => t.LastUpdated);
        string hex = BitConverter.ToString(results);
        hex =  hex.Replace("-", "");
        return hex;
    }

Timestamp is not da datetime thing: 时间戳不是日期时间的事情:

http://technet.microsoft.com/en-us/library/ms182776.aspx http://technet.microsoft.com/en-us/library/ms182776.aspx

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数据类型。

You can then use 然后你可以使用

long timeStampLong = BitConverter.ToInt64(value, 0);

to get a long back (and convert that long into string if you wish). 得到一个很长的回来(如果你愿意,可以把那个长的转换成字符串)。

I figured out how to do the conversion. 我想出了如何进行转换。

public string MaxDepartment() { public string MaxDepartment(){

    CPLinkEntities _context = new CPLinkEntities();
    var results = _context.LOG_Departments.Max(t => t.LastUpdated);
    string hex = BitConverter.ToString(results);
    hex =  hex.Replace("-", "");
    return hex;
}

it could be something like this: 它可能是这样的:

yourDBContext context=new yourDBContext();
var maxTimestamp = context.yourTable.Max(t => t.Timestamp);

I'd prefer to see this for more detail on working with linq. 关于使用linq的更多细节,我更愿意看到这一点

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

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