EntityFrameWork SaveChanges错误

时间:2014-07-08 21:53:08

标签: asp.net-mvc entity-framework

我正在尝试使用Entity Framework(代码优先)对数据库进行更改。一切正常,直到我尝试保存更改时,抛出错误:

  

无效的列名称BasketID

但是,在调试期间,查看storeDB.BasketItems,实际上已添加basketitem

我错过了什么?

代码:

// Basket is ENTIRELY Empty, add new item and move on.
if (storebasket == null || storebasket.BasketItems.Count == 0)
{
   // Add item as is
   BasketItem newItem = new BasketItem
              {
                sellerSKU = basketItem.sellerSKU,
                BasketID = basketID,
                sellerID = 1,
                Quantity = basketItem.Quantity,
                Price = basketItem.Price
              };

   storeDB.BasketItems.Add(newItem);
   storeDB.SaveChanges();
}

数据库实体:

public class StoreEntities : DbContext
{
    public DbSet<Order> Order { get; set; }
    public DbSet<OrderItems> OrderItems { get; set; }
    public DbSet<Basket> Basket { get; set; }
    public DbSet<BasketItem> BasketItems { get; set; }
}

类:

public class Basket
{
    [Key]
    public string BasketID { get; set; }

    public virtual IList<BasketItem> BasketItems { get; set; }
    public System.DateTime DateCreated { get; set; }
    public Guid UserID { get; set; }
}

public class BasketItem
{
    [Key]
    public int BasketItemID { get; set; }

    public virtual string BasketID { get; set; }
    [Required]
    public int sellerID { get; set; }
    [Required]
    public string sellerSKU { get; set; }
    [Required]
    public int Quantity { get; set; }
    [Required]
    public decimal Price { get; set; }
}

OP粘贴编辑为答案:

我不知道为什么这样可以解决问题,但程序现在按预期工作

public StoreEntities(): base("storeDBConnectionString") 
 {
     Database.SetInitializer<StoreEntities>(
           new DropCreateDatabaseAlways<StoreEntities>());

1 个答案:

答案 0 :(得分:0)

如果查看您的BasketItem类,则将BasketID设置为虚拟...这会导致实体框架不将属性绑定到列。正确的方法是:

public class BasketItem
{
[Key]
public int BasketItemID { get; set; }

public virtual Basket Basket { get; set; }

public string BasketID { get; set; }

[Required]
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
}