我正在使用實體框架和代碼優先使用一個項目。這裏是我縮短的類我的課在數據庫中創建條目,我希望它停止
public class BenefitsForm : IAnnualForm, IAuditable
{
public BenefitsUser UserInfo { get; set; }
public CoverageLevel Medical { get; set; }
}
public class MedicalPlan : IHealthPlan
{
public int Id { get; set; }
public virtual IList<CoverageLevel> CoverageLevels { get; set; }
}
public class CoverageLevel
{
public int Id { get; set; }
public virtual MedicalPlan MedicalPlan { get; set; }
}
在每個MedicalPlan有4個覆蓋水平。我已經有了數據庫中的覆蓋率和醫療計劃。但是,當我創建我的BenefitsForm時,它會爲這些類創建重複的條目(我已經在數據庫中擁有它們)。我怎樣才能阻止它做到這一點?這裏有一個小代碼片段來展示它是如何發生的。
BenefitsForm form = new BenefitsForm() { UserInfo = new BenefitsUser() };
using(var repo = new CoverageLevelRepository())
{
form.Medical = repo.Retrieve(new NumericKey(formId))); //this retrieves the coveragelevel with the id I want.
}
formRepository.Create(form); // this creates a duplicate med plan and 4 duplicate coverage levels.
formRepository.SaveChanges();
如果您知道在數據庫中創建重複條目的方法,請在創建數據庫之前確認它不存在。 – 2012-07-31 18:00:20