ASP.Net MVC C#模型与另一个模型的多个实例?

时间:2017-09-20 15:57:38

标签: c# asp.net models

我正在努力实现一个系统,工程师可以提出请求,而支持人员可以将请求分配给他/她自己,这样当有人试图在网站上显示请求时,它将显示创建请求的人员的姓名以及请求分配给的人员的姓名。

我的模特:

public class ConfigurationRequest
{
public virtual int     RequestId { get; set; }
public virtual int     UserId { get; set; }
public virtual int     RequestNumber { get; set; }
public virtual string  ReqDesc { get; set; }
}

public class User
{
public virtual int     UserId { get; set; }
public virtual string  UserRole {get; set; }
public virtual string  UserName {get; set; }
public virtual ICollection(ConfigurationRequest) ConfigurationReuquest { get; set; }
}

对于每个配置请求,我想在浏览器中显示以下内容:

请求编号:2864965

由(所有者)提出:戴夫约翰逊

目前已分配给:Mike Clarke

请求说明:燃油平衡系统所需的新要点

1 个答案:

答案 0 :(得分:1)

当两次引用同一个类时,您需要帮助实体框架找出如何匹配FK。您可以使用注释或流畅的代码。

public class ConfigurationRequest
{
    public int RequestId { get; set; }
    public int RequestNumber { get; set; }
    public string ReqDesc { get; set; }
    // EF will pair the below FK to nav by convention. You could also use ForeignKey attribute.
    public int RequestingUserId { get; set; }
    public User RequestingUser { get; set; }
    public int AssignedUserId { get; set; }  // make this int? if it is optional
    public User AssignedUser { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserRole {get; set; }
    public string UserName {get; set; }

    // you need a collection for each relationship. InverseProperty tells EF how to match them to User FK
    [InverseProperty("RequestingUser")]    
    public virtual ICollection<ConfigurationRequest> RequestsRaised { get; set; }
    [InverseProperty("AssignedUser")]    
    public virtual ICollection<ConfigurationRequest> RequestsAssigned { get; set; }
}

或流利的等价物:

modelBuilder.Entity<ConfigurationRequest>()
  .HasRequired(c => c.RequestingUser)   // or HasOptional()
  .WithMany(p => p.RequestsRaised);

modelBuilder.Entity<ConfigurationRequest>()
  .HasRequired(l => l.AssignedUser)
  .WithMany(p => p.RequestsAssigned);

有关详细信息,请参阅here。另外,请勿在非导航属性上使用virtual - 这些属性不会延迟加载。

现在,在您的控制器中,您可以获取请求,使用它来填充视图模型,并显示结果:

context.ConfigurationRequests
       .Include(c => c.RequestingUser)
       .Include(c => c.AssignedUser)
       .FirstOrDefault(c => c.RequestId == myRequestId);