c# - 为什么对 ObjectSet<T>.AddObject() 的调用会获取所有 T 类型的实体?

标签 c# entity-framework

var he = new LogHistoryEntry
             {
                 ActionId = action.Id,
                 ObjectId = logObject.Id,
                 UserId = user.Id,
                 Info = msg,
                 Item = s.Id,
                 Date = DateTime.Now
             };

ctx.LogHistoryEntries.AddObject(he);

我只想添加一个日志条目。我不希望 EF 读取已保存在数据库中的所有条目。 我怎样才能避免这种情况?

更新 1:

嗯,我不会称之为解决方案,但这种方法有效。

public static void LogChanges(ObjectContext context, string msg, int itemId, int userId, int logActionId, int logObjectId)
{
    context.ExecuteStoreCommand(
                "insert into log_history (object_id,action_id,item,info,user_id,date) values ({0},{1},{2},{3},{4},GETDATE())",
                logObjectId, logActionId, itemId, msg, userId);
}

但是,我不喜欢这样,因为从层分离的角度来看,这是一种 hack。 在这里我要知道存储列名称。那不行。

更新 2:

这是 sql-profiler 在调用 AddObject 时返回的内容:

exec sp_executesql N'SELECT [Extent1].[id] AS [id], [Extent1].[object_id] AS [object_id], [Extent1].[action_id] AS [action_id], [Extent1].[item] AS [item], [Extent1].[info] AS [info], [Extent1].[date] AS [date], [Extent1].[user_id] AS [user_id] FROM [dbo].[log_history] AS [Extent1] WHERE [Extent1].[user_id] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=4

当然,它不要求所有日志条目,但为什么它要检查给定的用户 ID 对我来说是个谜。

最佳答案

Hvd 是对的。数据库往返的原因是生成了具有修复和启用延迟加载的 POCO。

关于c# - 为什么对 ObjectSet<T>.AddObject() 的调用会获取所有 T 类型的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8258784/

相关文章:

C# 是否可以并行 foreach while 循环?

c# - 为什么submit类型的按钮会触发父组件中的OnInit

c# - Entity Framework 代码优先 6.0 : is there any annotations to add index to a column(s)

c# - .mdf 文件上的 Entity Framework

c# - 在 C# 中使用 HTTP 发送 PNG

c# - 通过 ApiController 将 JSON 发布到 Azure 队列

c# - 将所有日期存储为 BsonDocuments

c# - 添加到 ObjectSet<TEntity> 的对象的多态移除不会引发 ObjectSet<TEntity>.IListSource.GetList() 上的 IBindingList.ListChanged

entity-framework - 将 DbContext 注入(inject) FluentValidation 验证器

asp.net-mvc - ASP.NET MVC 动态添加子记录