How to display data from two tables code first EF ASP.NET MVC 5

时间:2016-04-21 22:24:32

标签: asp.net asp.net-mvc entity-framework asp.net-mvc-5

I'm trying to display data from two tables which are join with foreign key. My models:

public class Deal
{
    [Key]
    public int ID { get; set; }

    [Display(Name = "Client name")]
    public string ClientName { get; set; }

    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }
}

and

public class ApplicationUser : IdentityUser
{
    [Key]
    public override string Id { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    // FK
    public virtual ICollection<Deal> Deals { get; set; }
}

My controller:

// GET: Deal
public ActionResult Index()
{
    return View(db.Deals);
}

How can I display in View something like this:

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.NazwaKlienta)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.User.Nazwisko)!!!
    </td>
</tr>}

I always get error Invalid column name 'Discriminator'. @Html.DisplayFor(modelItem => item.User.Nazwisko)

1 个答案:

答案 0 :(得分:0)

如果您的ViewModel包含两个表的属性,则可以将实体的值分配给viewmodel的属性并最终显示它。

例如:

public class Deal
{
    [Key]
    public int ID { get; set; }

    [Display(Name = "Client name")]
    public string ClientName { get; set; }

    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }
}

public class ApplicationUser : IdentityUser
{
    [Key]
    public override string Id { get; set; }
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    public virtual ICollection<Deal> Deals { get; set; }
}

public class ViewModelTest
{
   public int DealId { get; set; }
   public string ClientName { get; set; }
   public string UserId { get; set; }

   public string ApplicationUserId { get; set; }
   public string FirstName { get; set; }
}

如果编写一些将实体值分配给ViewModel属性的代码,则可以使用viewmodel显示这两个实体。