开发者

Why are anonymous Types in EF4 different from LINQ to SQL ones?

开发者 https://www.devze.com 2023-03-13 19:28 出处:网络
I have the following query in LINQ to SQL to fetch all records from a Table that are not already in a jointable.

I have the following query in LINQ to SQL to fetch all records from a Table that are not already in a jointable.

// <param name="id">The ID of the Person</param>
IEnumberable<object> GetUnassignedClients(int id)
{
    _db.Clients
    .Select(i => new
    {
        Client_id = i.Id,
        Person_id = id,
        Cid = id + "." + i.Id // Please don't ask why I do this. I just have to do it
        // ... some more fields
    })
    .Where(o =>
        !_db.Clients_Persons
            .Where(t => t.Person_id == id)
            .Select(t => t.Client_id)
            .Contains(o.Client_id))
    .Distinct().ToList();
}

Now I have started a migration to EF4 but the "Cid" part of the anonymous type with the combination T开发者_运维技巧oList() (ToList() triggered the exception is a simplified testcase without the WHERE condition) fails with the exception:

Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

Why is that so or am I missing something here?


EF does not know how to translate the expression id + "." + i.Id into valid SQL which is why it fails. You have to tell EF that it needs to convert id from an integer to a string. You can do this using the SqlFunctions class in the following way:

var ret = _db.Clients
.Select(i => new
{
    Client_id = i.Id,
    Person_id = id,
    Cid = SqlFunctions.StringConvert((double) id) + "." + SqlFunctions.StringConvert((double) i.Id) // Please don't ask why I do this. I just have to do it
    // ... some more fields
})
.Where(o =>
    !_db.Clients_Persons
        .Where(t => t.Person_id == id)
        .Select(t => t.Client_id)
        .Contains(id)
)
.Distinct()
.ToList()
;
0

精彩评论

暂无评论...
验证码 换一张
取 消