简体   繁体   中英

entity framework object with sub-object save sub-object once

edit: made a little mistake in description

i have class User which has property of class Group

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

class Group {
    public int Id {get; set;}
    [Index(IsUnique = true)]
    public string Name {get;set;}
}

now i'm creating a list of User class which some of them might contain same class Group value

example data:

var users = new List<User> {
    new User {
        Name = "user1",
        Group = getGroup("admin2",..moreParams)
    },
    new User {
        Name = "user2",
        Group = getGroup("admin2",..moreParams)
    },
    new User {
        Name = "admin1",
        Group = getGroup("admin2",..moreParams)
    },
    new User {
        Name = "admin2",
        Group = getGroup("admin2",..moreParams)
    },
};

public Group getGroup(params){
    if(_cacheGroups.Any(someRule)){
        return _cacheGroups.First(someRule);
    }else{
        ... loading the correct group
    }
}

how do i prevent the entity framework from saving the group multiple times

currently exception message is

Duplicate entry 'users' for key 'IX_Name'

You are creating new instance of Group for each User , some of them has the same Name , that causes the error(The Name has unique Index). You must create one instance for each distinct Group and then assign the Group of each User based on them:

var admins =  new Group {
            Name= "admins",
        };
var users = new Group {
            Name= "users",
        };
var users = new List<User> {
    new User {
        Name = "user1",
        Group = users
    },
    new User {
        Name = "user2",
        Group = users
    },
    new User {
        Name = "admin1",
        Group = admins
    },
    new User {
        Name = "admin2",
        Group = admins
    },
};

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