簡體   English   中英

linq與sql一對一關系C#

[英]linq to sql one-one relationship C#

在表中的記錄創建之后,“客戶”必須占用ID。 后來的ID用於在“ Clients_details”中創建新條目。

        var user = GetUsers();
        var userdet = GetclientsDetails();

        string hashedpass = getMd5Hash(UIPassword.Text);

        var newreg = new Clients
        {
            login = UILogin.Text,
            password = hashedpass,
            subscribeid = Convert.ToInt32(UIId.Text)
        };

        user.InsertOnSubmit(newreg);
        user.Context.SubmitChanges();

        var details = new Clients_details
        {
            city = UICity.Text,
            first_name = UIFirst_name.Text,
            last_name = UIFamiliya.Text,
            name = UIName.Text,
            Clients = newreg
        };

        userdet.InsertOnSubmit(details);
        userdet.Context.SubmitChanges();

此代碼失敗后: “試圖對不是新的對象執行附加或添加操作,並且該對象可能是從另一個DataContext加載的。不支持此操作。”

數據庫語言

如何正確創建沒有出現錯誤的記錄? 謝謝!

    private static Table<Clients> GetUsers()
    {
        var dce = new BaseDBMLDataContext();
        return dce.Clients;
    }

    private static Table<Clients_details> GetclientsDetails()
    {
        var dce = new BaseDBMLDataContext();
        return dce.Clients_details;
    }

看起來像userdet.Contextuser.Context是使用不同的dataContext ,需要使用相同的dataContext創建而不是實例化一個新的dataContext。

我認為您只需要在最后只調用一次SubmitChanges,並且還需要確保您使用的用戶和userdet共享相同的上下文

正如錯誤明確指出的那樣,您要為每個實體使用不同的上下文(用戶和userdet)。 您應該具有一個DataContext並使用該DataContext添加實體。

是的,看起來您正在使用同一上下文的兩個不同實例:

user.Context.SubmitChanges();
userdet.Context.SubmitChanges();

建立實體的好方法應該是:

//Create your client details entity
var details = new Clients_details
{
    city = UICity.Text,
    first_name = UIFirst_name.Text,
    last_name = UIFamiliya.Text,
    name = UIName.Text    
};

//Create your client entity
var newreg = new Clients
{
    login = UILogin.Text,
    password = hashedpass,
    subscribeid = Convert.ToInt32(UIId.Text),
    //Assigning the details entity (FK) to the client
    ClientDetails = details
};

//Saving both the client and its details
user.InsertOnSubmit(newreg);
user.Context.SubmitChanges();

暫無
暫無

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

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