I have an EF question for you: I have these two classes
public class Post
{
public long Id {get;set}
public string Content {get;set;}
public virtual ICollection<Comment> Comments {get;set;}
}
public class Comment
{
public long Id {get;set;}
public string Content {get;set;}
}
I created a database at first with these columns and EF created foreign key with Id
column of Post
class, but then I added UniqKey
column as my new primary key:
public class Post
{
public long Id {get;set}
public string Content {get;set;}
public string UniqKey {get;set;} //New Field will be my new primary key
public virtual ICollection<Comment> Comments {get;set;}
}
and I want to change my foreign key to use UniqKey
instead of Id
.
I want to update database without deleting and losing any data.
Any help appreciated
Thanks
You should operate on database first (maybe with management studio if you are using SQLserver or with Toad preferred in this case).
First of all make a back-up of the database.
Then add the column UniqKey with allowed null.
Now update the table and add manually the value of UniqKey.
Remove the constraints and key relative to Id.
Remove allowed null to Uniqkey and add the constraint and the key to it.
In your model add the attribute [Key] and [DatabaseGenerated(DatabaseGeneratedOption.None)]
Don't forget you have to change also foreign key of Comments
Give a look here link1 and here link2 also.
If your database has only these two table you can also think to use database first approach, and use the new context created by wizard instead of old one you created with code-first approach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.