Dan*_*fer 5 .net c# datacontext executequery linq-to-sql
我编写了一个应用程序,我用它作为代理来查询数据库中的数据并自动将其加载到我的分布式Web缓存中.
我这样做是通过在配置中指定sql查询和类型.实际执行查询的代码如下所示:
List<Object> result = null;
try { result = dc.ExecuteQuery(elementType, entry.Command).OfType<Object>().ToList(); }
catch (Exception ex) { HandleException(ex, WebCacheAgentLogEvent.DatabaseExecutionError); continue; }
Run Code Online (Sandbox Code Playgroud)
elementType
是从配置(使用Type.GetType()
)中指定的类型创建的System.Type ,并且entry.Command
是SQL查询.
我遇到问题的特定实体类型如下所示:
public class FooCount
{
[Column(Name = "foo_id")]
public Int32 FooId { get; set; }
[Column(Name = "count")]
public Int32 Count { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
SQL查询如下所示:
select foo_id as foo_id, sum(count) as [count]
from foo_aggregates
group by foo_id
order by foo_id
Run Code Online (Sandbox Code Playgroud)
出于某种原因,在执行查询时,"Count"属性最终会填充,但不会填充"FooId"属性.我自己尝试运行查询,并返回正确的列名,列名与我在映射属性中指定的名称相匹配.救命!
疯了吧...
解决我的问题的是用以下方法装饰我的实体类TableAttribute
:
[Table(Name = "foo_aggregates")]
public class FooCount
{
[Column(Name = "foo_id")]
public Int32 FooId { get; set; }
[Column(Name = "count")]
public Int32 Count { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我假设(错误地,显然)因为我没有使用该GetTable<T>()
方法,所以我不需要相应的映射属性.
更新:一年半之后,它终于明白了,似乎属性上的ColumnAttribute装饰被忽略,除非在类上有相应的TableAttribute修饰.这解释了为什么"Count"属性被填充,因为它的命名将匹配SQL语句中的列,而FooId/foo_id当然不匹配.