簡體   English   中英

更新一對多表實體框架

[英]Update one to many table Entity Framework

我有一個“創建User ASP.NET MVC 3”頁面-該頁面上有一個多選汽車框,該框是從我的數據庫中的Cars表中預先填充的。 在保存用戶時,我返回與用戶關聯的CarId的整數列表。 我正在使用WCF服務和Entity Framework 5.0將數據返回到SQL Server並保存到SQL Server。

然后,我在數據庫CarUser中有一個表-它只包含一個用戶ID和一個客戶端ID-用戶表中的UserId和汽車表中的CarId分別為兩個FK。

當我創建一個用戶時,它正在更新CarUser表正在正確地更新(因此,例如-它可能看起來像這樣)

CarId用戶ID 2 4 3 4 4 4 5 4

因此它看起來正確,因為我的CarUser表顯示了與從“多重選擇”框中選擇的4個CarId相關聯的用戶4。 但是我遇到的問題是它正在汽車表中重新創建汽車-例如,它正在創建汽車ID 9,10,11,12,但它們的詳細信息與2,3,4完全相同,5

我為此編寫的代碼如下:

    public User User_Create(User user, List<int> carIds)
    {
        DAL.CarUserWCFFServiceImpl carUser = new DAL.CarUserWCFFServiceImpl();

        // cal the DAL layer to do the create
        User newUser = carUser.User_Create(user);

        //call the DAL layer to create the cars linked to a user
        carUser.CarUserMapping_Create(newUser.UserID, carIds);

因此,我的第一個DAL方法(位於列出該代碼的方法的下一層)調用創建了User-然后,一旦有了用戶,便有了ID,依此類推,我在DAL層調用了另一個方法,傳入了UserID作為新創建的用戶,然后是與該用戶關聯的carId列表。

下面是第二種方法的代碼:

    public void CarUserMapping_Create(int userId, List<int> carIds)
    {
        using (CUEntities entities = new CUEntities())
        {
            User user = User_GetById(userId);
            entities.Users.Attach(userId);

            foreach (int carId in carIds)
            {
                Car car = Car_GetById(carId);

                user.Cars.Add(car);
                entities.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Modified);
                entities.SaveChanges();
            }
        }
    }

誰能看到我做錯了什么? 我在想的另一種選擇是從Entity Framework移除它,然后在CarUserMapping_Create中調用存儲過程

也許您需要添加以下內容:

public void CarUserMapping_Create(int userId, List<int> carIds)
{
    using (CUEntities entities = new CUEntities())
    {
        User user = User_GetById(userId);
        entities.Users.Attach(userId);

        foreach (int carId in carIds)
        {
            Car car = Car_GetById(carId);
            car.UserID = user.UserID;
            entities.Entry(car).State = EntityState.Modified;
            entities.SaveChanges();
        }
    }
}

您不應該這樣設置狀態。 那就像強奸框架。

Instedad將模型實例( entities )作為參數傳遞給讀取讀取的汽車和用戶的方法。 (並且在方法中使用entities作為ObjectContext),如下所示:

using (CUEntities entities = new CUEntities())
{
    User user = User_GetById(entities , userId);


    foreach (int carId in carIds)
    {
        Car car = Car_GetById(entities, carId);
        car.UserID = user.UserID;
        entities.SaveChanges();
    }
}

這樣,實體框架將保持實體狀態范圍

暫無
暫無

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

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