运行迁移时,ASP.NET Core 2.1模型不断尝试在DB中创建ApplicationUsers表

时间:2019-01-23 08:32:23

标签: c# asp.net-core asp.net-core-mvc entity-framework-core

我有一个聊天项目引用了Auth项目。所引用的项目之一是

  

AuthProject.Data.Models;

包含一个名为ApplicationUsers的类。该表已经在数据库和模型“ ChatParticipant”中创建,我想使用ParticipantId对该表进行引用/外键。

indexes

但是,当我运行迁移时会发生什么,就是创建了一个新的ApplicationUsers表,而不是链接到旧的表。此应用程序与Auth项目共享相同的数据库。

如何防止创建ApplicationUsers?

Startup.cs dbContext定义

public class ChatParticipant
{
    public string Id { get; set; }
    public string SessionId { get; set; }
    public ChatSession Session { get; set; }
    public string ParticipantId { get; set; }
    public virtual ApplicationUsers Participant { get; set; }
}

ChatSampleDbContext:

services.AddDbContext<AuthProjectDbContext>(options => options.UseSqlServer(Configuration["DatabaseConfiguration:ConnectionString"]));
services.AddDbContext<ChatSampleDbContext>(options => options.UseSqlServer(Configuration["DatabaseConfiguration:ConnectionString"]));

AuthProject DbContext:

public ChatSampleDbContext(DbContextOptions<ChatSampleDbContext> options) : base(options) {

}
UniqueKeyGenerator uniqueKeyGenerator = new UniqueKeyGenerator();
public DbSet<ChatMessage> ChatMessage { get; set; }
public DbSet<ChatParticipant> ChatParticipant { get; set; }
public DbSet<ChatSession> ChatSession { get; set; }


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    IConfigurationRoot configuration = new ConfigurationBuilder()
    .SetBasePath(ConfigurationManager.GetBasePath(Environment.GetEnvironmentVariable("CENTRAL_APPLICATION_SETTINGS")))
    .AddJsonFile("cssettings.json")
    .Build();
    modelBuilder.HasDefaultSchema(schema: configuration["DatabaseSchemas:ChatSample"]);
    base.OnModelCreating(modelBuilder);
}

public override int SaveChanges()
{
    Audit();
    return base.SaveChanges();
}

public async Task<int> SaveChangesAsync()
{
    Audit();
    return await base.SaveChangesAsync();
}

private void Audit()
{
    var entries = ChangeTracker.Entries().Where(x => x.Entity is ChatSession && (x.State == EntityState.Added || x.State == EntityState.Modified));
    foreach (var entry in entries)
    {
        if (entry.State == EntityState.Added)
        {
            ((ChatSession)entry.Entity).CreatedOn = DateTime.UtcNow;
        }
    ((ChatSession)entry.Entity).CreatedOn = DateTime.UtcNow;
    }
}

0 个答案:

没有答案