简体   繁体   中英

EF model change one-to-one relationship to many-to-many relationship

I have two tables with one-to-one relationship.

    public class Name
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Category
    {
        public int Id { get; set; }
        public string Category { get; set; }
        public int? NameId { get; set; }

       [ForeignKey("NameId ")]
       public virtual Name Name { get; set; }
    }

I already have data in those tables.
I know the database relations are not supported to be changed.
Is it possible to change one-to-one relationships to many-to-many relationships?
What is the most suitable approach to overcome this requirement?

Yes, you can still change that, using migrations.

Step 1 is to create a linking table, like NameCategories, which looks something like this:

public class NameCategories
{
    public int Id { get; set; }
    
    public int NameId { get; set; }
    public Name Name { get; set; }
    
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

Step 2 is to reference this table in the tables you already have. In Name it would look like this

 public class Name
 {
    public int Id { get; set; }
    public string Name { get; set; }
    
    public virtual ICollection<NameCategory> Categories { get; set; }
 }

Step 3 is to add a migration . You'll have some AddColumn() and some DropColumn() statements. In between them, when all the add stuff was executed but the drops not yet, you can add SQL code to carry over all the existing relations into the newly created table. After that, the old data will be deleted by the DropColumn() code. In your example, this would look something like this

INSERT INTO NameCategories (NameId, CategoryId)
SELECT (n.Id, c.Id) FROM Names n
JOIN Categories c on c.NameId = n.Id
WHERE ..

You can execute the SQL in the migration like this:

var sql = @"...";
Sql(sql);

I hope this helps you out!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM