2

I have two class A and B. B has a foreign key to A.

class A {
     byte Id{get; set;}
     string Name{get;set;}
 }

and

class B {
     byte Id{get; set;}
     string Name{get;set;}
     A A{get;set;}
     byte AId{get;set;}
 }

My problem is:

  1. I created a class A with a property id of type int
  2. I run update-database
  3. I modified data type of id to byte
  4. I run update-database again
  5. I found that in table B that use id of A as the foreign key has two columns, i.e., aId and a_Id.

My question is: how can I remove the column a_Id using code first approach? Or anyway that is feasible.

I tried to run the query: ALTER TABLE DROP COLUMN a_Id - failed because one or more objects access this column.

I also tried to delete the column directly using VS Server explorer, remove the column by using table definition. But it did not work too.

Thanks

1
  • Should you provide A, B class source code? "text" question will get back text answer Commented Apr 29, 2017 at 9:20

4 Answers 4

1

Just follow these steps
1: Remove properties from the model.
2: Run 'Enable-Migrations' in package manage console.
3: Next Run 'Add-Migration "MigrationsName"'. if any case it is showing 'The project tesproject failed to build then build project again.
4: Now run 'Update-Database'

Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by remove properties from the model? Remove A related properties from B, e.g., id??
The property that you are trying to remove from database table
0

Perhaps you forgot to change B's FK type in the model.

[Required]
public byte ClassAId{ get; set; }

public virtual ClassA ClassA{ get; set; }

Also check out what you have in your migration's Up and Down methods.

Attribute [Key] over classA's Id could also be useful.

Comments

0

You Can Comment B class and Update-database! (drop table) again update-database with B class! :) for me this work!

Comments

0

I faced the same problem while I was learning ASP.net the solution to delete the unwanted prop is the following:

1- you have to delete it as an index so add new migration and write this instruction in the UP method

    DropIndex("dbo.TableName", new[] { "ColumnName" });

2- update-database note: at this phase you can make sure that the index has gone if you open the definition of the table (SQL code)

3- New migration but now write in the Up method

 DropColumn("TableName", "ColumnName");

4- Update-database

and it's gone

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.