【发布时间】:2023-03-18 20:24:02
【问题描述】:
我有一个表Batches,其中DispatchBy 和DispatchTo 链接到一个主键表:Users。
在视图中,我使用以下代码从 Users 表中获取 DispatchBy UserName。如何获得DispatchTo UserName?
@foreach ( var item in Model.Batches)
{
<tr>
<th>@item.User.UserName</th>
<th>@item.DispatchByStatus</th>
<th>@item.DispatchByTimestamp</th>
<th>@item.User1.UserName</th>
<th>@item.DispatchToStatus</th>
<th>@item.DispatchToTimestamp</th>
</tr>
}
表格:批次
CREATE TABLE [dbo].[Batches] (
[BTransactionID] INT IDENTITY (1, 1) NOT NULL,
[BatchID] INT NULL,
[TaxPayerTIN] VARCHAR (9) NOT NULL,
[Qty] INT NOT NULL,
[DispatchBy] INT NOT NULL,
[DispatchByStatus] VARCHAR (11) NOT NULL,
[DispatchByTimestamp] DATETIME NOT NULL,
[DispatchTo] INT NULL,
[DispatchToStatus] VARCHAR (11) NULL,
[DispatchToTimestamp] DATETIME NULL,
CONSTRAINT [PK_Batch] PRIMARY KEY CLUSTERED ([BTransactionID] ASC),
CONSTRAINT [FK_Batches_Users1] FOREIGN KEY ([DispatchTo]) REFERENCES [dbo].[Users] ([UserID]),
CONSTRAINT [FK_Batches_Users] FOREIGN KEY ([DispatchBy]) REFERENCES [dbo].[Users] ([UserID])
);
表格:用户
CREATE TABLE [dbo].[Users] (
[UserID] INT IDENTITY (1, 1) NOT NULL,
[UserName] VARCHAR (255) NOT NULL,
[UserEmail] VARCHAR (255) NOT NULL,
[UserPassword] VARCHAR (255) NOT NULL,
[UserPasswordSalt] VARCHAR (255) NULL,
[UserRoleID] INT NOT NULL,
[DepartmentID] INT NOT NULL,
[UserCreated] DATETIME NOT NULL,
[UserStatus] VARCHAR (11) NOT NULL,
CONSTRAINT [PK_Users_1] PRIMARY KEY CLUSTERED ([UserID] ASC),
CONSTRAINT [FK_Users_Departments] FOREIGN KEY ([DepartmentID]) REFERENCES [dbo].[Departments] ([DepartmentID]),
CONSTRAINT [FK_Users_Roles] FOREIGN KEY ([UserRoleID]) REFERENCES [dbo].[Roles] ([RoleID])
);
模型:Batch.cs
public partial class Batch
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Batch()
{
this.Collections = new HashSet<Collection>();
}
public int BTransactionID { get; set; }
public Nullable<int> BatchID { get; set; }
public string TaxPayerTIN { get; set; }
public int Qty { get; set; }
public int DispatchBy { get; set; }
public string DispatchByStatus { get; set; }
public System.DateTime DispatchByTimestamp { get; set; }
public Nullable<int> DispatchTo { get; set; }
public string DispatchToStatus { get; set; }
public Nullable<System.DateTime> DispatchToTimestamp { get; set; }
public virtual User User { get; set; }
public virtual User User1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Collection> Collections { get; set; }
}
【问题讨论】:
-
<th>@item.User.UserName</th>?我建议将Batch类中的User和User1属性重命名为有意义的名称(例如:DispatchToUser、DispatchByUser),让您的生活更轻松。
标签: c# asp.net-mvc entity-framework linq