简体   繁体   中英

Adding data in Entity Framework in tables with Foreign Key

I am struggling to Insert data in a table with Foreign key relationship.I did read a
few articles on how to do this but did not help much and decided to open up a new question.

Scenario :

User table has a foreign key on role table ID.

On the role table Id is integer and is auto incremented

Here is my code,

        SalesTrainerEntities db = new SalesTrainerEntities();

        var user = new User();
        var role = db.Role.FirstOrDefault(r => r.ID == 1);

        user.UserName = "test";
        user.Pass = "123";
        user.CreatedBy = "test";
        user.DtCreated = DateTime.Now;
        user.Role = role;

        //user.RoleId = 1;
        //user.EntityKey = new EntityKey("Role", "ID", 1);
        //user.RoleReference.EntityKey = new EntityKey("Role", "ID", 1);

        db.AddToUser(user);

        db.SaveChanges();

On Save Changes I get error stating

Unable to update the EntitySet 'User' because it has a DefiningQuery and no    <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

Any pointers will be highly appreciated.

Regards,

Sab

I used to add children entities this way, I'm assuming a relation 1:N between user and role.

using (Entities db = new Entities())
{              
    var user = new User();
    // fill user data..

    var newRole = db.Role.FirstOrDefault(r => r.ID == 1);
    if(newRole!=null)
    {
        user.roles.AddObject(newRole);
        db.users.AddObject(user);
        db.SaveChanges();
    }
}

//Edit - Updating db

using (Entities db = new Entities())
{ 
    var existingUser = db.User.FirstOrDefault(r => r.ID == 100);
    if(existingUser !=null)
    {
       existingUser.Name = "New name";
       db.SaveChanges();
    }
}

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