0

I am using the Identity DB context and the Application DB context, I have a table (UserVehicles) in which I did foreign key reference with the ApplicationUser(Identity User) property, when I add migration for the ApplicationDBContext it is creating the script for new table "ApplicationUser" and adding foreign key relation to the new table instead of the default AspnetUsers(Identity User) table. Below are the classes

IdentityDBContext class

public class ApplicationUser : IdentityUser<int>
{
    [PersonalData]
    public string FirstName { get; set; }
    [PersonalData]
    public string LastName { get; set; }
}

ApplicationDBContext class

[Table("UserVehicles")]
public class UserVehicle
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    [MaxLength(50, ErrorMessage = "Name maximum length is 50.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Tracker unique id is required.")]
    public string TrackerUniqueId { get; set; }

    [Required(ErrorMessage = "Server host is required.")]
    public string ServerHost { get; set; }

    public bool IsActive { get; set; }

    [Required(ErrorMessage = "User is required.")]
    [ForeignKey("ApplicationUser")]
    public int UserId { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }
}

below is the migration that is created

protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "ApplicationUser",
            columns: table => new
            {
                AccessFailedCount = table.Column<int>(nullable: false),
                EmailConfirmed = table.Column<bool>(nullable: false),
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                LockoutEnabled = table.Column<bool>(nullable: false),
                LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
                PhoneNumberConfirmed = table.Column<bool>(nullable: false),
                TwoFactorEnabled = table.Column<bool>(nullable: false),
                UserName = table.Column<string>(nullable: true),
                NormalizedUserName = table.Column<string>(nullable: true),
                Email = table.Column<string>(nullable: true),
                NormalizedEmail = table.Column<string>(nullable: true),
                PasswordHash = table.Column<string>(nullable: true),
                SecurityStamp = table.Column<string>(nullable: true),
                ConcurrencyStamp = table.Column<string>(nullable: true),
                PhoneNumber = table.Column<string>(nullable: true),
                FirstName = table.Column<string>(nullable: true),
                LastName = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_ApplicationUser", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "UserVehicles",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Name = table.Column<string>(maxLength: 50, nullable: false),
                TrackerUniqueId = table.Column<string>(nullable: false),
                ServerHost = table.Column<string>(nullable: false),
                IsActive = table.Column<bool>(nullable: false),
                UserId = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_UserVehicles", x => x.Id);
                table.ForeignKey(
                    name: "FK_UserVehicles_ApplicationUser_UserId",
                    column: x => x.UserId,
                    principalTable: "ApplicationUser",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });
    }

I tried to remove the code for ApplicationUser in migration class also update the table name to Identity Users Table name and update the database then when I do query on the UserVehicles table I am getting "ApplicationUser table does not exist"

  • Are you sure the migration is performed on the same database? Perhaps it takes some default connection string instead of the one you expect. –  Aug 26 '18 at 21:08
  • @RuardvanElburg yes I am using the same connection string, below is from the ConfigureServices services.AddDbContext(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"))); – Sandeep QI Aug 27 '18 at 01:29
  • @RuardvanElburg can you help on this – Sandeep QI Aug 29 '18 at 02:06
  • That is why you'd better not mix contexts. Read my answer here for explanation: https://stackoverflow.com/questions/51934680/add-relationships-to-the-applicationuser-class-in-asp-net-identity-database-fir/52008503#52008503 You can try without adding UserVehicle to the Identity context. –  Aug 30 '18 at 06:43

1 Answers1

0

I had same issue once but had also navigation properties on the other side. The resolve this I used InverseProperty attribute.

Maybe this will work.

public class ApplicationUser : IdentityUser<int>
{
    /// Your others props...

    public virtual ICollection<UserVehicle> Vehicles { get; set; }
}

[Table("UserVehicles")]
public class UserVehicle
{
    /// Your others props...

    [InverseProperty("Vehicles")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}
Selmir
  • 1,136
  • 1
  • 11
  • 21
  • I tried with Inverse property in ForiegnKey Table and ICollection property in ApplicationUser table but still the migration is created for ApplicationUser table creation. @Roxtar – Sandeep QI Aug 23 '18 at 22:54