【问题标题】:Relation 1-to-many in MVC-5 withMVC-5 中的一对多关系
【发布时间】:2017-06-18 14:18:21
【问题描述】:

我正在尝试在网上商店项目中创建购买历史,我希望历史类从购物车中获取产品,我从未做过多对一的关系(我认为最适合情况),你怎么看?

    public class Clothes
        {
            [Key]
            public int Id { get; set; }


            public ClothesType Type { get; set; }

            public int Amount { get; set; }

            [Range(10, 150)]
            public double Price { get; set; }

            public string ImagePath { get; set; }

            public virtual History historyID { get; set; }
        }

public class History
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int historyID { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public DateTime ShipDate { get; set; }
        public int Price { get; set; }
        public virtual ICollection<Clothes> HistClothes { get; set; }
    }

【问题讨论】:

  • 您的命名似乎令人困惑。一个History(那是什么)有很多“衣服”?一个具有复数名称的类似乎很奇怪......

标签: c# asp.net model-view-controller asp.net-mvc-5 webshop


【解决方案1】:

命名约定!如果您希望历史记录有很多衣服,而衣服只有一个历史记录,那么下面的代码会很好用,这实际上没有意义:

[Table("Clothes")]
public class Clothe
    {
        [Key]
        public int Id { get; set; }
        public ClothesType Type { get; set; }
        public int Amount { get; set; }
        [Range(10, 150)]
        public double Price { get; set; }
        public string ImagePath { get; set; }
        public History historyID { get; set; } 
    }

public class History
{
    [Key]
    public int historyID { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public DateTime ShipDate { get; set; }
    public int Price { get; set; }
    public virtual ICollection<Clothe> ClothesHistory { get; set; }

    public History()
    {
        ClothesHistory = new List<Clothe>();
    }
}

如果您希望同一件衣服有多个历史记录,而每个历史记录只有一件衣服,则此代码运行良好:

[Table("Clothes")]
public class Clothe
    {
        [Key]
        public int Id { get; set; }
        public ClothesType Type { get; set; }
        public int Amount { get; set; }
        [Range(10, 150)]
        public double Price { get; set; }
        public string ImagePath { get; set; }
        public ICollection<History> Histories { get; set; } 

        public History()
        {
            Histories = new List<History>();
        }
    }

public class History
{
    [Key]
    public int historyID { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public DateTime ShipDate { get; set; }
    public int Price { get; set; }
    [Required]
    public Clothe RelatedClothe { get; set; }
}

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2013-11-20
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多