标签: dbcontext

每个网络请求一个DbContext ...为什么?

我一直在阅读很多文章,解释如何设置实体框架,DbContext以便每个HTTP Web请求只使用各种DI框架创建和使用一个.

为什么这首先是一个好主意?使用这种方法有什么好处?在某些情况下这是个好主意吗?在使用DbContext存储库方法调用实例化s 时,您是否可以使用此技术执行某些操作?

c# asp.net entity-framework dependency-injection dbcontext

382
推荐指数
6
解决办法
9万
查看次数

实体框架:一个数据库,多个DbContexts.这是一个坏主意吗?

我的印象是DbContext意味着代表你的数据库,因此,如果你的应用程序使用一个数据库,你只需要一个DbContext.但是,有些同事希望将功能区域分解为单独的DbContext类.我相信这来自一个好地方 - 希望保持代码清洁 - 但它似乎不稳定.我的直觉告诉我这是一个坏主意,但不幸的是,我的直觉并不是设计决策的充分条件.

所以我正在寻找A)为什么这可能是一个坏主意的具体例子,或B)保证这一切都很好.

entity-framework ef-code-first dbcontext entity-framework-4.3

193
推荐指数
8
解决办法
10万
查看次数

如何使用Entity Framework仅更新一个字段?

这是桌子

用户

UserId
UserName
Password
EmailAddress
Run Code Online (Sandbox Code Playgroud)

和代码..

public void ChangePassword(int userId, string password){
//code to update the password..
}
Run Code Online (Sandbox Code Playgroud)

sql entity field entity-framework-4 dbcontext

180
推荐指数
10
解决办法
18万
查看次数

实体类型<type>不是当前上下文的模型的一部分

我正在进入实体框架,但我不确定我是否错过了代码优先方法中的关键点.

我正在使用基于https://genericunitofworkandrepositories.codeplex.com/的代码的通用存储库模式,并创建了我的实体.

但是当我尝试访问或修改实体时,我会遇到以下情况:

System.InvalidOperationException:实体类型Estate不是当前上下文的模型的一部分.

当我尝试从我的存储库访问它时会发生这种情况:

public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}
Run Code Online (Sandbox Code Playgroud)

数据库(./SQLEXPRESS)创建得很好,但实体(表)不是在启动时创建的.

我想知道我是否需要显式设置实体的映射?EF不能自己做到这一点吗?

我的实体是:

public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
} 
Run Code Online (Sandbox Code Playgroud)

我的背景如下:

public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework ef-code-first dbcontext

135
推荐指数
6
解决办法
20万
查看次数

如何使用DbContext和SetInitializer修复datetime2超出范围的转换错误?

我正在使用Entity Framework 4.1中引入的DbContext和Code First API.

数据模型使用的基本数据类型,如stringDateTime.我在某些情况下使用的唯一数据注释是[Required],但这不是任何DateTime属性.例:

public virtual DateTime Start { get; set; }
Run Code Online (Sandbox Code Playgroud)

的DbContext子类也很简单,看起来像:

public class EventsContext : DbContext
{
    public DbSet<Event> Events { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Event>().ToTable("Events");
    }
}
Run Code Online (Sandbox Code Playgroud)

初始化设置日期在模型中有意义的值在今年或明年.

但是,当我运行初始化程序时,我收到此错误context.SaveChanges():

将datetime2数据类型转换为日期时间数据类型会导致超出范围的值.该语句已终止.

我不明白为什么会发生这种情况,因为一切都很简单.我也不确定如何解决它,因为没有edmx文件可以编辑.

有任何想法吗?

.net c# entity-framework ef-code-first dbcontext

132
推荐指数
7
解决办法
16万
查看次数

LINQ to Entities仅支持使用IEntity接口转换EDM原语或枚举类型

我有以下通用扩展方法:

public static T GetById<T>(this IQueryable<T> collection, Guid id) 
    where T : IEntity
{
    Expression<Func<T, bool>> predicate = e => e.Id == id;

    T entity;

    // Allow reporting more descriptive error messages.
    try
    {
        entity = collection.SingleOrDefault(predicate);
    }
    catch (Exception ex)
    {
        throw new InvalidOperationException(string.Format(
            "There was an error retrieving an {0} with id {1}. {2}",
            typeof(T).Name, id, ex.Message), ex);
    }

    if (entity == null)
    {
        throw new KeyNotFoundException(string.Format(
            "{0} with id {1} was not found.",
            typeof(T).Name, id));
    }

    return …
Run Code Online (Sandbox Code Playgroud)

.net c# entity-framework expression-trees dbcontext

89
推荐指数
3
解决办法
3万
查看次数

如何强制Entity Framework始终从数据库中获取更新数据?

我正在使用EntityFramework.Extended库来执行批量更新.唯一的问题是EF无法跟踪库执行的批量更新.因此,当我DbContext再次查询时,它不会返回更新的实体.

我发现AsNoTracking()在查询时使用方法会禁用跟踪并从数据库中获取新数据.但是,由于EF不跟踪查询的实体AsNoTracking(),因此无法对查询的数据执行任何更新.

有没有办法强制EF在跟踪变化时获取最新数据?

c# asp.net-mvc entity-framework dbcontext

79
推荐指数
3
解决办法
7万
查看次数

如何在我的程序中从DbContext.SaveChanges()记录生成的SQL?

根据这个帖子,我们可以记录生成的SQLvia EF,但是怎么样DbContext.SaveChanges()?没有任何额外的框架,有没有简单的方法来完成这项工作?

c# sql logging entity-framework dbcontext

77
推荐指数
4
解决办法
6万
查看次数

实体框架5深度复制/克隆实体

我正在使用Entity Framework 5(DBContext),我正在尝试找到深度复制实体的最佳方法(即复制实体和所有相关对象),然后将新实体保存在数据库中.我怎样才能做到这一点?我已经研究过使用扩展方法,CloneHelper但我不确定它是否适用DBContext.

dbcontext entity-framework-5

69
推荐指数
2
解决办法
4万
查看次数

c#entity framework:在您的repository类中正确使用DBContext类

我曾经实现过我的存储库类,如下所示

public Class MyRepository
{
      private MyDbContext _context; 

      public MyRepository(MyDbContext context)
      {
          _context = context;
      }

      public Entity GetEntity(Guid id)
      {
          return _context.Entities.Find(id);
      }
}
Run Code Online (Sandbox Code Playgroud)

However I recently read this article which says that's a bad practice to have data context as a private member in your repository: http://devproconnections.com/development/solving-net-scalability-problem

Now, theoretically the article is right: since DbContext implements IDisposable the most correct implementation would be the following.

public Class MyRepository
{
      public Entity  GetEntity(Guid id)
      {
          using (MyDbContext context = …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework dbcontext

68
推荐指数
4
解决办法
5万
查看次数