I can not get data from SQL Server via Entity Framework - asp.net-mvc

I try to implement a basic web site that uses EF in ASP.NET MVC. Simply put, I try to connect SQL database and list them. I have a Product model. However, nothing comes to the screen. Here is my Product class:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
A repository pattern has been used in the Project. So interface IProductRepository here:
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
Here is the Product Controller in the project. It is the only controller in entire solution:
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
this.repository = productRepository;
}
public ViewResult List()
{
//This is not the part of the original project. In order to make sure that the code interacts with
//the database.
if (repository.Products.Count() == 0)
{
NinjectControllerFactory nin = new NinjectControllerFactory();
IKernel kernel = nin.GetNinjectKernel();
this.repository = kernel.Get<IProductRepository>();
}
return View(repository.Products);
}
}
Default route has been set there. Here is the content of the List.cshtml
#model IEnumerable<Model.Product>
#{
ViewBag.Title = "List";
}
<h2>List</h2>
#foreach (var p in Model)
{
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
I connect to my local database, define a table, populate it. I inserted connection string to the web.config of the project:
add name="EFDbContext" connectionString="Data
Source=(localdb)\v11.0;Initial Catalog=efver1;Integrated
Security=True" providerName="System.Data.SqlClient"
Here is the EFProductRepository.cs
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
}
and here is the EFDbContext.cs:
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
I am using Ninject as a dependency injector. Here it is :
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext
requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
}
public IKernel GetNinjectKernel()
{
return this.ninjectKernel;
}
}
I made necessary changes here:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Burası da önemli.
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
However, only page I can see is a blank screen as follows :
What I am missing here? thanks in advance.
edit 1:
Here is the data inside local database:

add name="EFDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=efver1;Integrated Security=True" providerName="System.Data.SqlClient"
You are not connecting to the right database. According to the screenshot, your data is in INT-0014\SQLEXPRESS, not (localdb)\v11.0.

Related

StudentDbContext is null using Asp.net Core Web api

am a beginner in ASP.NET Core. I am creating a Web API service. While I am fetching the data from the database, I had a problem. What is the error I got? I have successfully done the database migration part and created the database successfully.
StudentDbContext is null
StudentController
namespace webb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private StudentDbContext studentDbContext;
public StudentController(StudentDbContext studentDbContext)
{
studentDbContext = studentDbContext;
}
// GET: api/<EmployeeController>
[HttpGet]
public IEnumerable<Student> Get()
{
// var studens = studentDbContext.Student;
return studentDbContext.Student;
}
}
}
Model
public class Student
{
public int id { get; set; }
public string stname { get; set; }
public string course { get; set; }
}
}
StudentDbContext
public class StudentDbContext : DbContext
{
public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options)
{
}
public DbSet<Student> Student { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=ams;Integrated Security=True; TrustServerCertificate = True");
}
}
IDataService
public interface IDataService<T>
{
Task<IEnumerable<T>> GetAll();
Task<T> Get(int id);
Task<T> Create(T entity);
Task<bool> Delete(T entity);
Task<T> Update(T entity);
}
}
I have successfully done the database migration part and created the
database successfully. StudentDbContext is null
Well, two mistake has been done. Your model has no primary key. So you will always get null data when there is no primary key set to your table column.
Therefore, your model should be as following:
Model:
public class Student
{
[Key]
public int id { get; set; }
public string stname { get; set; }
public string course { get; set; }
}
Controller:
Another misake is here studentDbContext.Student; this will not bring anything. You would be liking to fetch student list instead. So you should write studentDbContext.Student.ToList();. As following"
[HttpGet]
public IEnumerable<Student> Get()
{
// var studens = studentDbContext.Student;
return studentDbContext.Student.ToList();
}
Note: In addition, your constructor convension is not correct, it can be written as following:
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly StudentDbContext _studentDbContext;
public StudentController(ApplicationDbContext studentDbContext)
{
_studentDbContext = studentDbContext;
}
// GET: api/<EmployeeController>
[HttpGet]
public IEnumerable<Student> Get()
{
// var studens = studentDbContext.Student;
return _studentDbContext.Student.ToList();
}
}
Note: You can check more details on asp.net core web api official document here
Output:
For further details you can have a look on official document here.

What unit test method can I write for the Delete action using xunit and moq?

public class Product
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public int Price { get; set; }
}
public class ProductService : IProductService
{
private readonly DataBaseContext _context;
public ProductService(DataBaseContext context)
{
_context = context;
}
public Product GetById(long id)
{
return _context.Products.Find(id);
}
public void Remove(long id)
{
var product = _context.Products.Find(id);
_context.Products.Remove(product);
_context.SaveChanges();
}
}
I created the following code using scaffolding and I want to write a test using xunit and moq:
public class ProductController : Controller
{
private readonly IProductService _productService;
public ProductController(IProductService productService)
{
_productService = productService;
}
// GET: ProductController/Delete/5
public ActionResult Delete(int id)
{
return View(_productService.GetById(id));
}
// POST: ProductController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
_productService.Remove(id);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
I installed the following packages on the main project And I made the relevant settings in startup:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.InMemory
I installed the following packages on the test project:
Moq
What unit test method can I write for the Delete action?
I would write 2 tests specifically for the delete function of your service. For the controller, I would probably do test using WebApplicationFactory to do the whole flow (caveat, I’m not 100% sure this is possible with mvc controllers).
For the service test, I would want to know: what happens when I pass in an id that exists? What happens when I pass in an id that doesn’t exist (Should it throw an exception etc)?
Both simply done by building your in memory database in your test and calling your service code. You can then validate that the database has removed the record with id “x”.
Example:
[Fact]
Public void WhenDeletingItsmThatExistsInDatabase_ShouldRemoveFromDatabase()
{
var ctx = new DbContext();
ctx.Products.Add(product with id 1);
ctx.SaveChanges():
var sut = new ProductService(ctx);
sut.Delete(1);
Assert.Empty(ctx.Products);
}

Database not created Code first EF

I do not understand why my code does not work. I have a model:
public class Client
{
public int Id { get; set; }
public string Surname { get; set; }
}
I have a Context:
public class BetContext : DbContext
{
public BetContext()
: base("name=Bet")
{
}
public virtual DbSet<Client> Clients { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
My ConnectionString:
<connectionStrings>
<add name="Bet" providerName="System.Data.SqlClient" connectionString="Data Source=PK01; Initial Catalog=Bet;Integrated Security=True; MultipleActiveResultSets=True" />
</connectionStrings>
My GlobalAsax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
Database.SetInitializer(new InitializerDb());
}
My ConnectToServer:
ConnectToServer
My Initializer:
public class InitializerDb : DropCreateDatabaseIfModelChanges<BetContext>
{
protected override void Seed(BetContext context)
{
var client = new List<Client>
{
new Client
{
Id = 1 , Surname = "Lalala" , Name = "Paxan" , DateOfBirthday = DateTime.Now, Email = "lalll",
Password = "123445" , Phone = "12345"
}
};
client.ForEach(s => context.Clients.Add(s));
context.SaveChanges();
}
}
I am stuck. Please tell me why this code is not creating a new database in SQL Server?

Create database using code first Entity Framework in SQL Server

I am using code first EF and new to this framework. I am trying to create a database using Database.SetInitializer but it looks like I need SQL Server Express. But I have to create database in SQL Server 2014. How to do this?
Can anybody explain this with the example from EF-dbcontext book which has following classes.
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Activity> Activities { get; set; }
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());
try
{
using (var context = new BreakAwayContext())
{
foreach (var destination in context.Destinations)
Console.WriteLine(destination.Name);
}
}
catch(Exception ex){
Console.WriteLine(ex.ToString());
}
Console.Read();
}
}
public class InitializeBagaDatabaseWithSeedData : DropCreateDatabaseAlways<BreakAwayContext>
{
protected override void Seed(BreakAwayContext context)
{
context.Destinations.Add(new Destination
{
Name = "Hawaii",
Country = "USA",
Description = "Sunshine, beaches and fun."
});
context.Destinations.Add(new Destination
{
Name = "Wine Glass Bay",
Country = "Australia",
Description = "Picturesque sandy beaches."
});
}
Set your connection string in your constructor:
public class BreakAwayContext : DbContext
{
public BreakAwayContext()
: base("MyConnectionString", throwIfV1Schema: false)
{
}
...
Then set your connection string in web.config or app.config:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=servername;Initial Catalog=dbname;..." providerName="System.Data.SqlClient" />
</connectionStrings>

How To Use CRUD in ASP.Net MVC with EntityFramework CodeFirst in Pattern IUnitofwork

I Have a PhoneBook Project in MVC and use IUnitOfWork .
but I dont Know that How do this project.
the link of the project :
http://www.mediafire.com/download/jy0b5ins5eisy5t/MvcAppPhoneBook.rar
please complate thie project for me
i'm doing CRUD in this project.
I've used generic repo and UoW in my projects as below. You can take reference of this to complete your project. I usually have 4 layer solution architecture:
Core
Model classes
Data
Generic Repo and UoW
DbContext
Code first migrations
Web
applications solution with dependency injection implementation (e.g.Ninject)
Test
Model classes
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
}
MyDbContext.cs:
public class MyDbContext : DbContext
{
public MyDbContext() : base("name=DefaultConnection”)
{
}
public System.Data.Entity.DbSet<User> Users { get; set; }
public System.Data.Entity.DbSet<Course> Courses { get; set; }
}
Unit of Work:
public class UnitOfWork : IUnitOfWork
{
//private variable for db context
private MyDbContext _context;
//initial db context variable when Unit of Work is constructed
public UnitOfWork()
{
_context = new MyDbContext();
}
//property to get db context
public MyDbContext Context
{
//if not null return current instance of db context else return new
get { return _context ?? (_context = new MyDbContext()); }
}
//save function to save changes using UnitOfWork
public void Save()
{
_context.SaveChanges();
}
}
Generic Repository:
public class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected readonly IUnitOfWork _unitOfWork;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dbSet = _unitOfWork.Context.Set<T>();
}
public virtual void Save()
{
_unitOfWork.Save();
}
public virtual void Add(T entity)
{
_dbSet.Add(entity);
_unitOfWork.Save();
}
//Similarly you can have Update(), Delete(), GetAll() implementation here
}
Entity Repository inheriting from generic repo:
public class UserRepository:RepositoryBase<User>,IUserRepository
{
public UserRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
//Here you can also define functions specific to User
}
controller.cs
public class UserController : Controller
{
private readonly IUserRepository _dbUserRepository;
public UserController(IUserRepository dbUserRepository)
{
_dbUserRepository = dbUserRepository;
}
// GET: /User/
public ActionResult Index()
{
var users = _dbUserRepository.GetAll();
return View(users.ToList());
}
//Other CRUD operations
}

Resources