EntityFramework一对一或零

时间:2015-05-26 20:49:15

标签: c# entity-framework

我的“ShoppingCart”和“ShoppingCartItems”表已经在我的数据库中。我正在尝试添加一个名为“discountCodes”的新表。每个shoppingCart都可以有一个或零个discountCodes。

我收到的错误是:列名'discountId'无效。

[Table("ShoppingCarts")]
    public class ShoppingCart
    {


        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        [Column("cartID")]
        public string cartID { get; set; }
        public virtual IList<ShoppingCartItem> CartItems { get; set; }
        [Column("dateCreated")]
        public DateTime? DateCreated { get; set; }
        [Column("userID")]
        public Guid UserID { get; set; }
        public int? discountId { get; set; }
        public virtual Discount discount { get; set; }
    }

    [Table("discountCodes")]
    public class Discount
    {

        public int discountId { get; set; }
        public string discountCode{get;set;}
        [Required]
        public int percentOff { get; set; }
        [Required]
        public Boolean isActive { get; set; }
        public  ShoppingCart ShoppingCart { get; set; }

    }
public class ShoppingCartContext : DbContext
{

    public ShoppingCartContext()
        : base("MYDBConnectionString")
    {
        Database.SetInitializer<ShoppingCartContext>(new CreateDatabaseIfNotExists<ShoppingCartContext>());

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ShoppingCart>().HasKey(t => t.cartID)
                     .HasOptional(t => t.discount)
                     .WithOptionalPrincipal(d => d.ShoppingCart)
                     .Map(t => t.MapKey("cartID")); 
        modelBuilder.Entity<Discount>().HasKey(t => t.discountId)
                    .HasOptional(q => q.ShoppingCart);
    }   
    public DbSet<Discount> discountCodes { get; set; }
    public DbSet<ShoppingCart> ShoppingCart { get; set; }
    public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }

}

1 个答案:

答案 0 :(得分:0)

如果您正在使用现有数据库,则必须实施DbMigration,例如:Code First Migrations

如果您处于开发阶段,最简单的方法是删除数据库。