首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC-5中的一对多关系

MVC-5中的一对多关系
EN

Stack Overflow用户
提问于 2017-06-18 22:18:22
回答 1查看 28关注 0票数 0

我试图在一个网上商店项目中创造购买的历史,我希望类历史有购物车中的产品,我从来没有做过多对一的关系(我认为是最适合的),你觉得呢?

代码语言:javascript
复制
    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; }
    }
EN

回答 1

Stack Overflow用户

发布于 2017-06-19 05:51:48

命名约定!如果你想要一个历史有很多衣服,而一件衣服只有一个历史,那么下面的代码很好用,这是没有实际意义的:

代码语言:javascript
复制
[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>();
    }
}

相反,如果您希望同一件衣服有多个历史记录,而每个历史记录只有一件衣服,则此代码效果很好:

代码语言:javascript
复制
[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; }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44615914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档