asp.net 2属性引用相同的类

本文关键字:引用 net 属性 asp | 更新日期: 2023-09-27 17:58:33

我有一个名为Client的模型类。

namespace Logistic.Models
{
    public class Client
    {
        public int ClientId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public ICollection<Dispatch> dispatches { get; set; }
    }
}

我有另一个类,它有两个与客户端相关的属性:

namespace Logistic.Models
{
    public class Dispatch
    {
        public int DispatchId { get; set; }
        public int CustomerId { get; set; }
        public int RecipientId { get; set; }
        public Client Customer { get; set; }
        public Client Recipient { get; set; }
    }
}

为了在Dispatch类中建立关系,我必须具有clientId。正确的但在这种情况下,我将有两个clientId。我刚开始使用ASP。NET MVC,我无法理解它。

asp.net 2属性引用相同的类

因为在我的控制器中我有:

public ActionResult Dispatch()
        {
            db.Dispatches.Include("Customer").ToList();
            db.Dispatches.Include("Recipient").ToList();
            var dispatch = db.Dispatches;
            return View(dispatch);
        }

在我看来,我正试图显示:

@model IEnumerable<Logistic.Models.Dispatch>
@{
    ViewBag.Title = "Dispatch";
}
<h2>Dispatch</h2>
@foreach(var item in Model)
{
    <h2>Tracking : @item.TrackingId</h2> <br />
    <h2>Customer : @item.Customer.Name</h2> <br />
    <h2>Recipient : @item.Recipient.Name</h2> <br />
}

如果我理解正确,您正试图将RecipientId和CustomerId分别用作收件人和客户的外键?在这种情况下,您可以将外键属性添加到属性中,如下所示:

namespace Logistic.Models
{
    public class Dispatch
    {
        public int DispatchId { get; set; }
        public int CustomerId { get; set; }
        public int RecipientId { get; set; }
        [ForeignKey("CustomerId")]
        public Client Customer { get; set; }
        [ForeignKey("RecipientId")]
        public Client Recipient { get; set; }
    }
}

这将明确指定关系的外键。希望这能有所帮助!