Guid: How can I get latest inserted record via LINQ to Entites?

c# entity-framework-6 guid linq

Question

I'm using below code to fetch latest inserted record:

public Request GetLastRequest()
{
    return _request.Find(_request.Max(p => p.Id));
}

As you can see Id is type of Guid:

public class Request
{
        public Request()
        {
            Id = Guid.NewGuid();
        }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

}

After running my code, I'm getting this error:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

PS: above code works if I use int for Id.

1
2
1/24/2015 12:40:40 AM

Accepted Answer

You'll need to timestamp the record or put an auto-incrementing int on the record - GUIDs are generated randomly, so they won't actually represent a "max" GUID after insertion.

If your main intent is to get the record after inserting it, you could generate the GUID in your application layer and insert it into the database, this way you can return the GUID you just inserted in order to query back into the database for your information.

4
1/3/2015 2:08:31 PM

Popular Answer

This works with int because entity framework can translate the Max()-linq-method to the appropriate sql-function. But it fails for Guid as they are not supported.

Take a look at this (scroll down to MAX( expression )): http://msdn.microsoft.com/en-us/library/bb399163%28v=vs.110%29.aspx

A Collection (T) where T is one of the following types: Byte, Int16, Int32, Int64, Byte, Single, Double, Decimal, DateTime, DateTimeOffset, Time, String, Binary.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow