efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Is this bug in db migrations

Open dewebeloper opened this issue 10 years ago • 3 comments

I have three entity:

public class PropertyTenant
    {
        public PropertyTenant()
        {
            Users = new List<User>();
        }
        public string Id { get; set; }
        public string RefNumber { get; set; }
        public TenantStatus Status { get; set; }
        public RentalPropertyDetail  RentalPropertyDetail { get; set; }
        public ICollection<User> Users { get; set; }
        public Rent Rent { get; set; }
    }
public class FlatLessee
    {
        public FlatLessee()
        {
            Users = new List<User>();
        }
        public string Id { get; set; }
        public string FlatId { get; set; }
        public LesseeStatus Status { get; set; }
        public Flat Flat { get; set; }
        public ICollection<User> Users { get; set; }
        public DateTime CompletationDate { get; set; }
        public DateTime TransferNoticaDate { get; set; }
        public bool  HasBeenExtended { get; set; }
        public int NewTerm { get; set; }
        public decimal NewGroundRent { get; set; }
        public DateTime  NewGroundIncreaseDate { get; set; }
    }

and

public class User
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Tel { get; set; }
        public string Address { get; set; }
        public string ParentId { get; set; } // fk for flatlessee and propertytenant
        public FlatLessee FlatLessee { get; set; }
        public PropertyTenant PropertyTenant { get; set; }

    }

in user mapping I wish to make relationship PropertyTenant.Id to User.ParentId and FlatLessee.Id to User.ParentId like this:

user.HasOne(r => r.PropertyTenant)
                .WithMany(r => r.Users)
                .HasForeignKey(f => f.ParentId)
                .OnDelete(DeleteBehavior.Restrict);

            user.HasOne(r => r.FlatLessee)
             .WithMany(r => r.Users)
             .HasForeignKey(f => f.ParentId)
             .OnDelete(DeleteBehavior.Restrict);

After I create migrations (first migration), in migration class I have this:

migrationBuilder.CreateTable(
                name: "User",
                columns: table => new
                {
                    Id = table.Column<string>(maxLength: 128, nullable: false),
                    Address = table.Column<string>(maxLength: 500, nullable: false),
                    Email = table.Column<string>(maxLength: 50, nullable: true),
                    FirstName = table.Column<string>(maxLength: 30, nullable: false),
                    LastName = table.Column<string>(maxLength: 30, nullable: false),
                    ParentId = table.Column<string>(maxLength: 128, nullable: false),
                    PropertyTenantId = table.Column<string>(nullable: true),
                    Tel = table.Column<string>(maxLength: 25, nullable: false),
                    Title = table.Column<string>(maxLength: 10, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_User", x => x.Id);
                    table.ForeignKey(
                        name: "FK_User_FlatLessee_ParentId",
                        column: x => x.ParentId,
                        principalTable: "FlatLessee",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_User_PropertyTenant_PropertyTenantId",
                        column: x => x.PropertyTenantId,
                        principalTable: "PropertyTenant",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

Where PropertyTenantId is non existing field in my entity. Strange thing is if I change order of mapping lines like this:


            user.HasOne(r => r.FlatLessee)
             .WithMany(r => r.Users)
             .HasForeignKey(f => f.ParentId)
             .OnDelete(DeleteBehavior.Restrict);

            user.HasOne(r => r.PropertyTenant)
                .WithMany(r => r.Users)
                .HasForeignKey(f => f.ParentId)
                .OnDelete(DeleteBehavior.Restrict);

Migration will create a little bit different code:

 migrationBuilder.CreateTable(
                name: "User",
                columns: table => new
                {
                    Id = table.Column<string>(maxLength: 128, nullable: false),
                    Address = table.Column<string>(maxLength: 500, nullable: false),
                    Email = table.Column<string>(maxLength: 50, nullable: true),
                    FirstName = table.Column<string>(maxLength: 30, nullable: false),
                    FlatLesseeId = table.Column<string>(nullable: true),
                    LastName = table.Column<string>(maxLength: 30, nullable: false),
                    ParentId = table.Column<string>(maxLength: 128, nullable: false),
                    Tel = table.Column<string>(maxLength: 25, nullable: false),
                    Title = table.Column<string>(maxLength: 10, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_User", x => x.Id);
                    table.ForeignKey(
                        name: "FK_User_FlatLessee_FlatLesseeId",
                        column: x => x.FlatLesseeId,
                        principalTable: "FlatLessee",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_User_PropertyTenant_ParentId",
                        column: x => x.ParentId,
                        principalTable: "PropertyTenant",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

Where I now have FlatLesseeId, instead previous PropertyTenantId. Is this bug, or I'. doing something wrong? Cheers

UPDATE: When I manually changed migration code, I was able to generate DB with correct relationships. But When I try to add user to Db I get issue "Invalid column name 'FlatLesseeId'". Here is stack.

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues, Boolean manageConnection)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)

dewebeloper avatar Oct 07 '16 08:10 dewebeloper

@dewebeloper - Which version of EF are you using? The behavior you are seeing is because 2nd relationship is removing first one and creating it by convention so FK property you get is different from what you configured. Ordering changes which relationship will get ParentId as FK (last one will get it). Shared FK property should be supported. There may be something going on with inverse navigation being with same name.

smitpatel avatar Oct 07 '16 14:10 smitpatel

I'm using EF core 1.0.0. So for now that is expected behavior.? "Shared FK property" is term wen we have two different relationship to same FK, right? Like Table1.Id to Table3.ParentId and Table2.Id to Table3.ParentId. Is there any example how to configure shared FK property properly?
Cheers

dewebeloper avatar Oct 08 '16 15:10 dewebeloper

Above configuration works fine with 1.1.0-preview1 release available publicly.

smitpatel avatar Oct 26 '16 20:10 smitpatel