使用struct而不是类的EntityFramework SqlQuery失败,出现ArgumentException [英] EntityFramework SqlQuery using struct instead of class fails with ArgumentException

查看:62
本文介绍了使用struct而不是类的EntityFramework SqlQuery失败,出现ArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理EntityFramework应用程序,并且在使用结构而不是Database.SqlQuery类时遇到了一个问题。

I'm working on an EntityFramework application and I have run across a problem when using a struct instead of a class with Database.SqlQuery.

结构看起来像

internal struct Column
{
    public int object_id { get; set; }
    public string name { get; set; }
}

对SqlQuery的调用如下:

and the call to SqlQuery looks like this:

using (var db = new DbContext("ConnectionString"))
{
    var columns = db.Database.SqlQuery<Column>(query);
    DoSomething(columns.ToList()); // Exception thrown here
}

我收到一个ArgumentException,消息为表达式类型如果Column是结构,则'MyService.Column'不能用于返回类型'System.Object'。我将其更改为一个类,并且可以正常工作。

I get an ArgumentException with the message "Expression of type 'MyService.Column' cannot be used for return type 'System.Object'" when Column is a struct. I changed it to a class and it works fine.

我很高兴在这里使用一个类,但是我想知道为什么在

I'm happy enough to use a class here, but I'm wondering why a struct would fail when used in this way.

推荐答案

EntityFramework提供了数据的面向对象表示。因此,结果必须是一个对象,因为它必须保持状态。如果使用结构,则每次在方法之间传递列时都将复制数据,这是没有意义的,因为它表示数据库中的相同值。

EntityFramework provides an object oriented representation of your data. Because of that, the result needs to be an object, as it has to maintain state. If you use a struct, the data will be copied every time you pass the column between methods and that makes no sense, as it represent the same value from the database.

这篇关于使用struct而不是类的EntityFramework SqlQuery失败,出现ArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆