加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – DbContext继承更新 – 数据库错误

发布时间:2020-12-15 22:00:54 所属栏目:百科 来源:网络整理
导读:我们首先使用EntityFramework代码 我想实现DbContext继承: public class AgileDbContextBase : DbContext{ public DbSetAccount Accounts { get; set; } public DbSetUser Users { get; set; } protected override void OnModelCreating(DbModelBuilder mod
我们首先使用EntityFramework代码
我想实现DbContext继承:

public class AgileDbContextBase : DbContext
{
    public DbSet<Account> Accounts { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // base.OnModelCreating(modelBuilder);
        // TODO configure relations here!
        modelBuilder.Configurations.Add(new AccountEntityConfiguration())
            .Add(new UserEntityConfiguration());
    }
}

public class LoadContext : AgileDbContextBase
{
    #region Public Properties
    public DbSet<ProjectLoadEstimate> ProjectLoadEstimates { get; set; }
    public DbSet<OccupationType> OccupationTypes { get; set; }
    public DbSet<LoadReport> LoadReports { get; set; } 
    #endregion

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new ProjectLoadEstimateConfiguration())
            .Add(new OccupationTypeEntityConfiguration())
            .Add(new LoadReportEntityConfiguration());
    }
}

其中一个实体使用AgileDbContextBase上下文中的另一个实体,这里是:

public class LoadReport : BaseEntity
{
    /// <summary>
    ///     The date of load report has been created
    /// </summary>
    public virtual DateTime Created { get; set; }

    /// <summary>
    ///     The project manager
    /// </summary>
    public User ProjectManager { get; set; }

    /// <summary>
    ///     The Id of project manager
    /// </summary>
    public int ProjectManagerId { get; set; }
}

两个上下文都在使用自动迁移.
问题是,当我尝试在LoadContext上更新数据库时,PackageManager说

There is already an object named ‘Accounts’ in the database.

看起来它试图重新创建已经存在的表.怎么避免呢?
如何告诉代码优先来自LoadContext它必须在数据库中创建唯一的表,这些表被定义为DbSet<>在LoadContext中?
(也许是一些解决方法)?
附:两个上下文都使用相同的连接字符串.

感谢您的时间!

解决方法

重写OnModelCreating方法并配置模型构建器以忽略所需的实体.

查看此博客文章了解更多详情
http://msdn.microsoft.com/en-us/data/jj591617.aspx

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读