Adding a new relation to existing database using entity framework

。_饼干妹妹 提交于 2019-12-24 06:29:47

问题


Given a database with a table A. I want to create a table B and add a one-to-may relation between A and B with a required foreign key. For example suppose that have an existing table 'Users' and then we want to add 'Roles' to the existing users. The code first definition of those entities is as follows:

    public class User
    {
        public Id UserId { get; set; }
        public string Email { get; set; }
        public string UserName => Email;
        public Roles Role { get; set; }
        public int? RoleId { get; set; }
    }
    public class Roles
    {
        public string RoleName { get; set; }
        public int RoleId { get; set; };
        public ICollection<User> GetUsers { get; set; }
    }

The Configure Method for the Users using Fluent API is as follows:

    public void Configure(EntityTypeBuilder<User> builder)
    {
            builder.ToTable("User");                
            builder.HasKey(t => t.UserId );
            builder.Property(t => t.UserId ).ValueGeneratedOnAdd();

        builder.HasOne(dt => dt.Role)
            .WithMany(d => d.GetUsers)
            .HasForeignKey(dt => dt.RoleId)
            .HasConstraintName("ForeignKey_UserRole")
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired();
    }

Trying to run the migration I got this error message:

'The ALTER TABLE statement conflicted with the FOREIGN KEY constraint'

By splitting this migration in two migrations and seeding the data between the them allowed me to build the new database:

  • The first one remove the constrain IsRequired on the Fluent APi definition of the User entity and allowing null value for the foreign key RoleId.
  • Then Seed the database
  • Add the second and last migration to enable the constrain of the required foreign key RoleID in the User entity and removing the allows null on the foreign key.

My question is related to if there is an strategy that allows to add a new relation using code first approach with a required foreign key using only one migration?

Thank you

Francisco

来源:https://stackoverflow.com/questions/49057874/adding-a-new-relation-to-existing-database-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!