簡體   English   中英

在帶有外鍵的表中添加實體框架中的數據

[英]Adding data in Entity Framework in tables with Foreign Key

我正在努力在具有外鍵關系的表中插入數據。我確實閱讀了
很少有關於如何做到這一點的文章,但沒有多大幫助,並決定提出一個新問題。

設想 :

用戶表在角色表 ID 上有一個外鍵。

在角色表上,Id 是整數並且是自動遞增的

這是我的代碼,

        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();

在保存更改時,我收到錯誤說明

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.

任何指針將不勝感激。

問候,

薩布

我曾經以這種方式添加子實體,我假設用戶和角色之間的關系為 1:N。

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM