簡體   English   中英

實體框架將實體插入數據庫中

[英]Entity Framework Inserts the entity Already Exists in Database

我正在使用EF 6 Code-First MVC和Identity

我已經自定義了Identity框架中定義的標准ApplicationUser類,當我嘗試通過我的網頁注冊新用戶時,EF嘗試插入數據庫中已經存在的實體。

//some code above here

using (ApplicationDbContext db = new ApplicationDbContext())
{
    // I load the City object form db based on the model passed to current method
    City city = db.Countries.Include("States.Cities")
        .First(c => c.Code == model.CountryCode)
        .States.First(s => s.Id == model.StateId)
        .Cities.First(ci => ci.Name == model.CityName);

    // I create a new Employee and a new Company and Company has an Address 
    // referring to the City I loaded from db
    Employee employee = new Employee
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        Company = new Company
        {
            Name = model.CompanyName,
            OfficePhone = model.OfficePhone,
            Address = new Address { City = city, Street = model.Street, ZipCode = model.ZipCode }
        }
    };

    // This is part of Identity framework code
    var user = new ApplicationUser
    {
        UserName = model.Email,
        Email = model.Email,
        // my custom code: I assign employee to the standard ApplicationUser class
        UserProfile = employee
    };

    // This is going to save the new user to database, 
    // but it tries to insert a new Country object into db. 
    // Note that City class has a property of type State 
    // and State class has a property type of Country 
    var result = await UserManager.CreateAsync(user, model.Password);

    // more code below

基於我收到的錯誤,聽起來像EF將國家(地區)實體插入數據庫。 我想這是在EF向數據庫添加地址時發生的。 在我的代碼中,“地址”是新對象,但“城市”,“州”和“國家/地區”已經存在,您會看到我從一開始就從db加載“城市”。 所以我嘗試使用下面的代碼,但沒有幫助:

db.Entry(employee.Company.Address.City).State = EntityState.Unchanged;

很抱歉,冗長的代碼,但是我嘗試將其最小化。

這是我的模型:

public class Country
{
    string Code;
    string Name;
    List<State> States;
}

public class State
{
    int Id;
    string Name;
    List<City> Cities;
}

public class City
{
    int Id;
    string Name;
    State State;
}

public class Address
{
    string Street;
    string ZipCode;
    City City;
}

public class Company
{
    string Name;
    string OfficePhone;
    Address Address;
}

問題是,您每次都在創建新對象。 您需要先執行測試以查看用戶是否存在,如果存在,然后使用現有數據填充對象並使用Update。 因此,您還需要考慮使用UserManager.UpdateAsync方法。

很久以前我也遇到過類似的問題。 我不知道問題所在,但是有一種解決方法:

替換代碼:

var result = await UserManager.CreateAsync(user, model.Password);

使用以下代碼:

var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var result = UserManager.Create(user, model.Password);

這樣可以正確保存數據。

暫無
暫無

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

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