你如何先通过代码查找表

时间:2013-04-16 17:06:23

标签: ef-code-first

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

这是我的模特:

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;

    }

2 个答案:

答案 0 :(得分: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;
    ....
}

您还可以向DepartmentId类添加StoreDepartment并设置其值,就像使用StoreId一样。与Department属性一起,这称为foreign key association

答案 1 :(得分: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对象的外键。