asp.net 2属性引用同一个类

时间:2016-07-26 00:14:38

标签: c# asp.net asp.net-mvc

我有一个名为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; }
    }
}

我有另一个类,它有两个与Client有关系的属性:

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,我无法理解它。

2 个答案:

答案 0 :(得分:0)

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

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 />
}

答案 1 :(得分:0)

如果我理解正确,您是否尝试分别使用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; }
    }
}

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