显示数据库表中的数据

时间:2017-10-06 13:04:06

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

我正在尝试从数据库中获取数据以显示在我的视图中。目前在我的数据库表上有以下列:ID,ReportDescription,DateReported,CustomerId和MovieId。

我需要做的是使用CustomerId和MovieId来获取客户名称和电影名称。

这是我的模特:

public class Malfunction
{
    public int Id { get; set; }

    [Required]
    public Movie Movie { get; set; }

    [Required]
    public Customer Customer { get; set; }

    [Required]
    [StringLength(255)]
    public string ReportDescription { get; set; }

    public DateTime DateReported { get; set; }
}

这是控制器:

private ApplicationDbContext _context;

    public TablesController()
    {
        _context = new ApplicationDbContext();
    }
    // GET: Tables
    public ActionResult MalfunctionsList(MalfunctionDTO malfunctionDTO)
    {
        var malfunctions = _context.Malfunctions.ToList();

        return View(malfunctions);
    }
}

这就是DTO:

public class MalfunctionDTO
{ 
    public int CustomerId { get; set; }

    public List<int> MovieIds { get; set; }

    public Customer Customer { get; set; }

    public Movie Movie { get; set; }

    public string ReportDescription { get; set; }

}

IdentityModel:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<MembershipType> MembershipTypes { get; set; }
    public DbSet<Movie> Movies { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Genre> Genres { get; set; }
    public DbSet<Rent> Rents { get; set; }

    public DbSet<Malfunction> Malfunctions { get; set; }

我是否应该在我的模型中添加CustomerId和MovieId等属性才能使其正常工作? 值得注意的是我对MVC和EF很新,所以如果我有点困惑,请原谅我。

1 个答案:

答案 0 :(得分:0)

您需要将映射更改为如下所示。

//对于Id

Mapper.CreateMap<Malfunction, MalfunctionDTO>()
                .ForMember(dest => dest.CustomerId, 
                     opt => opt.MapFrom(src => src.Id));

<强>更新

我假设您没有使用Entity Framework Core。

更新您的上下文,如下所示。已添加vrtual个关键字。

public virtual DbSet<Movie> Movies { get; set; }
public virtual DbSet<Customer> Customers { get; set; }

同时更改

public class Malfunction
{
    public int Id { get; set; }

    [Required]
    public virtual Movie Movie { get; set; }

    [Required]
    public virtual Customer Customer { get; set; }

    [Required]
    [StringLength(255)]
    public string ReportDescription { get; set; }

    public DateTime DateReported { get; set; }
}

然后你可能需要在你的OnModelCreating方法中添加类似这样的配置。如果没有这个,请先尝试,如果不行,则添加以下配置。

modelBuilder.Entity()                 .WithRequired(m =&gt; m.Movie);

modelBuilder.Entity()                 .WithRequired(m =&gt; m.Customer);

相关问题