在Entity Framework中设置外键关系

时间:2018-05-15 20:20:48

标签: c# asp.net entity-framework asp.net-core-mvc entity-framework-core

我是ASP.Net和Entity Framework Core的新手,我正在开发一个简单的网络应用程序,用户可以在购物车和结帐时添加饮料。还有一个视图,其中包含用户的订单历史记录,这是我遇到问题的地方。每个订单都有一个订单行,该订单行是订单详细信息的列表。然而,当试图从orderdetail显示关于饮料的信息时,它说饮料无效。有谁知道这是为什么?谢谢

订单模型如下所示:

public class Order
{
    [BindNever]
    public int OrderId { get; set; }

    public string UserId { get; set; }

    public virtual List<OrderDetail> OrderLines { get; set; }

    [Required(ErrorMessage = "Please enter your first name")]
    [Display(Name = "First name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your last name")]
    [Display(Name = "Last name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please enter your address")]
    [StringLength(100)]
    [Display(Name = "Address Line 1")]
    public string AddressLine1 { get; set; }

    [Display(Name = "Address Line 2")]
    public string AddressLine2 { get; set; }

    [Required(ErrorMessage = "Please enter your zip code")]
    [Display(Name = "Zip code")]
    [StringLength(10, MinimumLength = 4)]
    public string ZipCode { get; set; }


    [Required(ErrorMessage = "Please enter your City")]
    [StringLength(50)]
    public string City { get; set; }

    [Required(ErrorMessage = "Please enter your State")]
    [StringLength(10)]
    public string State { get; set; }

    [Required(ErrorMessage = "Please enter your country")]
    [StringLength(50)]
    public string Country { get; set; }

    [Required(ErrorMessage = "Please enter your phone number")]
    [StringLength(25)]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Phone number")]
    public string PhoneNumber { get; set; }

    [Required]
    [StringLength(50)]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [BindNever]
    [ScaffoldColumn(false)]
    public decimal OrderTotal { get; set; }

    [BindNever]
    [ScaffoldColumn(false)]
    public DateTime DatePlaced { get; set; }
}

订单明细模型:

public class OrderDetail
{
    public int OrderDetailId { get; set; }

    public int OrderId { get; set; }

    public int DrinkId { get; set; }

    public string DrinkName { get; set; }

    public int Amount { get; set; }

    public decimal Price { get; set; }

    public Drink Drink { get; set; }

    public Order Order { get; set; }
}

在OrderRepository中创建Order方法:

    public void CreateOrder(Order order, string userId)
    {
        order.UserId = userId;

        order.DatePlaced = DateTime.Now;
        _appDbContext.Orders.Add(order);

        var shoppingCartItems = _shoppingCart.ShoppingCartItems;

        foreach (var item in shoppingCartItems)
        {
            var orderDetail = new OrderDetail()
            {
                Drink = item.Drink,
                Amount = item.Amount,
                DrinkId = item.Drink.DrinkId,
                DrinkName = item.Drink.Name,
                OrderId = order.OrderId,
                Price = item.Drink.Price
            };

            order.OrderTotal += item.Drink.Price*item.Amount;

            _appDbContext.OrderDetails.Add(orderDetail);
        }


        _appDbContext.SaveChanges();
    }

我还有一个OrderHistory ViewModel:

public class OrderHistoryViewModel
{
    public List<Order> OrderHistory { get; set; }
    public List<OrderDetail> OrderLines { get; set; }

}

控制器中的OrderHistory动作:

public async Task<ActionResult> MyAccount(OrderHistoryViewModel orderHistoryViewModel)
    {
        var user = await GetCurrentUserAsync();

        orderHistoryViewModel = new OrderHistoryViewModel
        {
            OrderHistory = _orderRepository.GetOrdersByCustomerId(user?.Id).ToList(),
            OrderLines = _orderRepository.GetOrderLines(_orderRepository.GetOrdersByCustomerId(user?.Id)).ToList()
        };

        return View(orderHistoryViewModel);
    }

我的帐户查看:

@model orderHistoryViewModel

        @foreach (var order in @Model.OrderHistory)
    {
        @foreach (var orderDetail in order.OrderLines)
        {

            decimal subtotal = orderDetail.Price * orderDetail.Amount;

                <div class="panel-body">
                    <div class="row">
                        <div class="col-md-3"><img src=@orderDetail.Drink.ImageUrl class="media-object thumbnail-image-xs"></div>
                        <div class="col-md-9">
                            <div class="row">
                                <div class="col-lg-12">
                                    <h4><span><strong>@orderDetail.Drink.Name</strong></span></h4>
                                </div>
                                <div class="col-md-12">
                                    <span style="font-weight:600">Quantity: </span> @orderDetail.Amount
                                </div>
                                <div class="col-md-12">
                                    <span style="font-weight:600">Price: </span> @subtotal

                                </div>
                                <div class="col-md-12">
                                    <span style="font-weight:600">Date Placed: </span> @order.DatePlaced.ToShortDateString()
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
        }
    }

OrdersByCustomerId和GetOrderLines的实现:

        public IEnumerable<Order> OrdersByCustomerId(string id)=> _appDbContext.Orders.Where(o => o.UserId == id).OrderByDescending(d => d.DatePlaced);

    public IEnumerable<OrderDetail> GetOrderLines(IEnumerable<Order> orderHistory)
    {
        List<OrderDetail> orderLines = new List<OrderDetail>();
        foreach (var order in orderHistory)
        {
            orderLines.AddRange(_appDbContext.OrderDetails.Where(od => od.OrderId == order.OrderId));
        }

        return orderLines;
    }

1 个答案:

答案 0 :(得分:0)

我将orderLines.AddRange(_appDbContext.OrderDetails.Where(od => od.OrderId == order.OrderId));更改为orderLines.AddRange(_appDbContext.OrderDetails.Where(od => od.OrderId == order.OrderId).Include(od => od.Drink);