Reputation: 7613
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:
A
with a property id
of type int
update-database
id
to byte
update-database
againB
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
Upvotes: 2
Views: 4143
Reputation: 1
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
Upvotes: 0
Reputation: 1
You Can Comment B class and Update-database! (drop table) again update-database with B class! :) for me this work!
Upvotes: 0
Reputation: 460
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.
Upvotes: 0
Reputation: 605
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'
Upvotes: 1