0

我一直在寻找这个没有任何运气如何解决。我有一个可以在我的商店中使用的可用部门列表。由于商店不同,有些部门可能不存在,我想跟踪每个部门为每个商店有多少货架空间。创建这个的最佳方法是什么?

这是我的模型:

public class Store
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; } //StoreNumber
    public virtual List<StoreDepartment> StoreDepartments { get; set; }
}

public class StoreDepartment
{
    [Key]
    public int ID { get; set; }
    public int StoreID { get; set; }
    public Department Department { get; set; }
    public int ShelvingLinealFT { get; set; }
}

public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; } //DepartmentNumber
    public string Name { get; set; }
    public bool InActive { get; set; }
}

我已经填充了我的部门表,但是当我尝试保存 StoreDepartment 对象时,我收到一条错误消息,指出它无法插入行,因为它试图创建重复键。这就像它试图创造一个新的记录。

任何帮助,将不胜感激。

这是我的 DbContext 的代码:

public class StoresRepository:DbContext
{
    public DbSet<Store> Stores { get; set; }
    public DbSet<StoreDepartment> StoreDepartments { get; set; }
    public DbSet<Department> Departments { get; set; }
}

这是我的保存方法:

    /// <summary>
/// Saves a StoreDepartment Object to the store("dept.storeid")
/// Adds a new record if ID is 0
/// </summary>
/// <param name="dept"></param>
/// <returns></returns>
public bool Save(StoreDepartment dept)
{
    bool retval = false;
    try
    {
        using (var db = new StoresRepository())
        {
            if (dept.ID.Equals(0))
            {
                //Add Store Department
                db.StoreDepartments.Add(dept);                            
            }
            else
            {
                //this is an update
                StoreDepartment  department = db.StoreDepartments.Where(p => p.ID.Equals(dept.ID)).FirstOrDefault();
                department.Department = dept.Department;
                department.ShelvingLinealFT = dept.ShelvingLinealFT;
            }
            int rowsupdated = db.SaveChanges();
            retval = true;
        }
    }
    catch (Exception ex)
    {
        Utils.Trace(string.Format("StoresContext.cs: StoreDepartments.Save(). ID:{1}. Exception: {0}", ex, dept.ID), Utils.ErrorTypes.Error);
    }
    return retval;

    }
4

2 回答 2

0

Department添加对象时,您可能会更改添加的StoreDepartment状态。像这样的东西:

using(var db = new MyContext())
{
    var storeDepartment = new StoreDepartment();
    storeDepartment.StoreId = storeId;
    storeDeparemtent.Department = department;
    db.StoreDepartments.Add(storeDepartment); // also marks Department as added
    db.SaveChanges();
}

解决方案是向上移动添加对象的行:

using(var db = new MyContext())
{
    var storeDepartment = new StoreDepartment();
    db.StoreDepartments.Add(storeDepartment);
    storeDepartment.StoreId = storeId;
    ....
}

您还可以将 a 添加DepartmentIdStoreDepartment类并设置其值,就像使用StoreId. 这与Department属性一起称为外键关联

于 2013-04-17T07:15:22.670 回答
0

我想到了。

以下是正确的模型:

public class StoreDepartment
{
    [Key]
    public int ID { get; set; }
    public int DepartmentID { get; set; }
    public virtual Department Department { get; set; }
    public int ShelvingFootage { get; set; }
}

public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public virtual ICollection<StoreDepartment> StoreDepartments { get; set; }
}

使用 Affluent API,我将我的关系设置如下:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StoreDepartment>().HasRequired(d => d.Department);
    modelBuilder.Entity<Department>().HasMany(d => d.StoreDepartments);            
}

完成此设置后,我遇到的主要问题之一就是填充对象。通常,您会执行以下操作:

StoreDepartment sd = new StoreDepartment();
sd.Department = new Department(){
    ID = 302,        
    Name = "Deli"
};
sd.ShelvingFootage = 100;

但是,当尝试保存此对象时,Entity 会尝试在 Department 表中添加一条新记录,这当然会由于主键冲突而引发异常。

诀窍是不直接更新它并按如下方式构建我的 StoreDepartment 对象:

StoreDepartment sd = new StoreDepartment();
sd.DepartmentID = 302;
sd.ShelvingFootage = 100;

通过这样做,您只是更新 StoreDepartment.Department 对象的外键。

于 2013-05-10T18:21:55.417 回答