Cant retrieve information from table in ASP.NET Entity Framework
Can't find why the object I'm supposed to retrieve from database is always empty, despite the fact that the table has 3 elements. In the view, Model.Count
is always == 0. New to dotnet, stuck for hours.
What I did :
- connection string in
app.config
- connection string in
web.config
<connectionStrings>
<add name="masterEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DBModel" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1 .msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;initial catalog=core2DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
- restart SQL Server
- Controller seems to know about my tables since it autocomplete tables and keys.
Posts.cs
namespace WebApplication1.Data
{
public partial class Posts
{
public int Id { get; set; }
public Nullable<int> Post_owner { get; set; }
public string Post_content { get; set; }
public Nullable<int> Post_like_count { get; set; }
public virtual Users Users { get; set; }
}
}
Model1.Context.Cs:
namespace WebApplication1.Data
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class DBModel : DbContext
{
public DBModel() : base("DBModel")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* Database.SetInitializer<DBModel>(null);
base.OnModelCreating(modelBuilder);*/
}
public virtual DbSet<Posts> Posts { get; set; }
public virtual DbSet<Users> Users { get; set; }
}
}
In PostController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Diagnostics;
namespace WebApplication1.Controllers
{
public class PostController : Controller
{
// GET: Post
public ActionResult Index()
{
var context = new DBModel();
List<Posts> postsList = new List<Posts>();
if (!context.Posts.Any())
{
/* postsList = 3;*/
}
postsList = context.Posts.ToList();
/* using (var context = new DBModel())
{
postsList = context.Posts.ToList();
}*/
return View(postsList);
}
}
}
and the view is (Index.cshtml) :
@model List<WebApplication1.Data.Posts>
@{
ViewBag.Title = "Index";
}
<h2>Hello Peyo</h2>
<div>@Model</div>
@foreach (var post in Model)
{
<div><span>Nom: </span><span>@post.Post_content</span></div>
}
<span>Hello again</span>