ApplicationDbContext.EntityName() returning null - asp.net-mvc

Why db.Countries() comes null in following scenario-
1. CityController
[Authorize]
public class CityController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext("CP");
// GET: City/Create
public ActionResult Create()
{
ViewBag.CountryId = new SelectList(db.Countries.ToList(), "CountryId", "Name");
return View();
}
ApplicationDbContext
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
internal IDbSet<Country> Countries { get; set; }
...
}
Country is defined as-
[Table("Country")]
public class Country
{
#region Fields
private ICollection<City> _cities;
#endregion
#region Scalar Properties
public Guid CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
#endregion
#region Navigation Properties
public virtual ICollection<City> Cities
{
get { return _cities ?? (_cities = new List<City>()); }
set { _cities = value; }
}
#endregion
}
City is defined as-
[Table("City")]
public class City
{
#region Fields
private ICollection<Location> _locations;
#endregion
#region Scalar Properties
public Guid CityId { get; set; }
public Guid CountryId { get; set; }
public string Name { get; set; }
public string CityCode { get; set; }
public string ZipCode { get; set; }
public Country Country { get; set; }
#endregion
#region Navigation Properties
public virtual ICollection<Location> Locations
{
get { return _locations ?? (_locations = new List<Location>()); }
set { _locations = value; }
}
#endregion
}
What could be the reason for not populating Country table records and returning countries to null?

After sparing few hours, I just noticed the Access-modifier of Countries properties which was internal. I made it Public and magic happened! It works though I don't have any explanation on WHY part of it.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
//internal IDbSet<Country> Countries { get; set; }
public IDbSet<Country> Countries { get; set; }
public IDbSet<City> Cities { get; set; }
Thanks everyone.

Related

I couldn't figure out the MVC Logic

Entity is:
public partial class Persons
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Surname { get; set; }
public string? Number { get; set; }
public string? Address { get; set; }
public string? PublicId { get; set; }
public string? FatherName { get; set; }
public string? MotherName { get; set; }
}
Also Model is:
public partial class OnlyPrivateProp
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Surname { get; set; }
}
And controller:
public class DemoController : Controller
{
_context c;
public DemoController(_context c)
{
this.c = c;
}
public IActionResult Index()
{
ET model= new ET();
var select = ..............
return View();
}
}
I dont want to use all data to display only three colunms. So I defined a model has three prop. But I cant pass data to model and cant select data and cant send controller.
You could create different ViewModel for different Views
The entities models are mapped to the tables in your database,you could check the documents related with EFCore
For your requirement,you could fill the viewmodel and pass the value to your View as below:
[Table("SomeTable")]
public class SomeEntity
{
public int Id { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
...........
}
public class ViewModel
{
public string Prop1 { get; set; }
public string Prop3 { get; set; }
}
public IActionResult SomeAction()
{
...........
var vmlist = _context.SomeEntity.Select(x => new ViewModel{ Prop1 = x.Prop1, Prop3 = x.Prop3 }).ToList();
return View(vmlist);
}
And the documents related with MVC

how to resolve web api error 'System.OutOfMemoryException'

I am creating ASP.Net MVC WebApi to share my data to bank. In this regard i have created an SQL View bit when i am testing my WebApi it is giving an 'System.OutOfMemoryException' error because i have more the 1 million record in SQL View.
My Code is given below:-
This is my controller
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.ToList();
}
}
public VBank_invoice Get(string consumer)
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.FirstOrDefault(e => e.consumer_no == consumer);
}
}
}
My SQL View Class
public partial class VBank_invoice
{
public int sno { get; set; }
public string consumer_no { get; set; }
public string consumer_name { get; set; }
public string consumer_address { get; set; }
public string billing_month { get; set; }
public Nullable<decimal> current_Charges { get; set; }
public Nullable<decimal> outstanding_Arrears { get; set; }
public Nullable<decimal> Arrears_15 { get; set; }
public Nullable<decimal> part_payment_arrears { get; set; }
public string billing_period_code { get; set; }
public string consumer_checkdigit { get; set; }
public Nullable<System.DateTime> due_date { get; set; }
}
This is my Model.Context.cs File
public partial class kmcEntities : DbContext
{
public kmcEntities()
: base("name=kmcEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<VBank_invoice> VBank_invoice { get; set; }
}
I believe you need to be serialize object model using the select query.
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.select(m => new {
m.sno, m.consumer_no,m.consumer_name, m.consumer_address,
m.billing_month, m.current_Charges, m.outstanding_Arrears,
m.Arrears_15, m.part_payment_arrears, m.billing_period_code,
m.consumer_checkdigit, m.due_date }).ToList();
}
}
}

Table Value Function mapping with Entity Framework 6.3

How do I map table value functions in Code with Entity Framework 6.3? I'm trying to a DB Context in code with an existing database, because EDMX is currently not supported in ASP.NET Core 3. I've tried setting up my DbContext clasee as below. I can successfully query the Grade table. But when I try to query my function "fn_GetCatgeories", I get the following error: No EdmType found for type 'WebApplication6.Data.ApplicationContext+fn_GetCategories'.
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories
{
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new FunctionsConvention<ApplicationContext>("dbo"));
base.OnModelCreating(modelBuilder);
}
[DbFunction("ApplicationContext", "fn_GetCategories")]
public IQueryable<fn_GetCategories> GetCategories(Nullable<System.DateTime> month)
{
var monthParameter = month.HasValue ?
new ObjectParameter("Month", month) :
new ObjectParameter("Month", typeof(System.DateTime));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<fn_GetCategories>(string.Format("[0].{1}", GetType().Name, "[fn_GetCategories](#Month)"), monthParameter);
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
}
This works:
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories_Result
{
[Key]
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
public DbSet<fn_GetCategories_Result> fn_GetCategoriesSet { get; set; }
public List<fn_GetCategories_Result> fn_GetCategories(DateTime month)
{
var m = new SqlParameter("Month", DateTime.Now);
return this.fn_GetCategoriesSet.SqlQuery("select * from dbo.fn_GetCategories(#month)", m).ToList();
}

How to create own/custom controller in Codefirst approach in entity framework

I am trying to make a sample application using code first approach in MVC so I don't have any database. Now I have setup all class files and context class. In next step I have created a controller(Emplty) and want to create own Create/List/Delete functionalities. How can I do it.
Some of the codes are below
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int DepartmentID { get; set; }//Foreign Key
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class EmployeeDBContext: DbContext
{
public EmployeeDBContext()
: base("EmployeeDBContext")//EmployeeDBContext will be name of database.
{ }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
}
public class EmployeeInitializer:DropCreateDatabaseIfModelChanges<EmployeeDBContext>
{
protected override void Seed(EmployeeDBContext context)
{
var employee = new List<Employee>
{
new Employee{EmployeeID=1, Name="Aman", Age=15, DepartmentID=11},
new Employee {EmployeeID=2, Name="Supriya", Age=12, DepartmentID=22},
new Employee {EmployeeID=3, Name="Rishabh", Age=10, DepartmentID=44}
};
employee.ForEach(x => context.Employees.Add(x));
context.SaveChanges();
var department = new List<Department> {
new Department{DepartmentID=11, DepartmentName="IT"},
new Department{DepartmentID=22, DepartmentName="HR"},
new Department{DepartmentID=33, DepartmentName="Mechanical"},
new Department{DepartmentID=44, DepartmentName="NGO"}
};
department.ForEach(x=>context.Departments.Add(x));
context.SaveChanges();
var enrollment = new List<Enrollment>() {
new Enrollment{EnrollmentID=111, EmployeeID=1, DepartmentID=11},
new Enrollment{EnrollmentID=222, EmployeeID=3, DepartmentID=44},
new Enrollment{EnrollmentID=333, EmployeeID=2, DepartmentID=22}
};
enrollment.ForEach(x=>context.Enrollments.Add(x));
context.SaveChanges();
}
}
I wish to add code from below controller onward
public ActionResult CreateEmployee(Employee employee)
{
//my desired code here
return View();
}
[HttpGet]
public ActionResult ListEmployee()
{
//my desired code here
return View();
}
you mean how to do something like:
[HttpGet]
public ActionResult ListEmployee()
{
//my desired code here
using(var context=new EmployeeDBContext())
{
return View(context. Employee.ToList());
}
}
[HttpPost]
[Route("api/Employee/CreateEmployee")]
public ActionResult CreateEmployee([FromBody]Employee employee)
{
//add to ef
_db.Add(employee);
_db.SaveChanges();
//my desired code here
return Ok();
}

DB Context - Query to select post from a category

I am using DB context approach in my asp.net mvc 4 test project.
Here are my domain classes
Category.cs
public class Categroy
{
public virtual int Id { get; set; }
public virtual string CategoryName{ get; set; }
public virtual ICollection<Post> Post{ get; set; }
}
Post.cs
public class Post
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
IPostsDateSource.cs
public interface IPostsDataSource
{
IQueryable<Category> Categories{ get; }
IQueryable<Post> Posts { get; }
void Save();
}
PostsDB.cs
public class PostsDB:DbContext,IPostsDataSource
{
public PostsDB():base("DefaultConnection")
{
}
public DbSet<Category> Categories{ get; set; }
public DbSet<Post> Posts{ get; set; }
void IPostsDataSource.Save()
{
SaveChanges();
}
IQueryable<Category> IPostsDataSource.Categories
{
get { return Categories; }
}
IQueryable<Post> IPostsDataSource.Posts
{
get { return Posts; }
}
}
I am using StructureMap for mapping
IoC.cs
...
x.For<IPostsDataSource>().HttpContextScoped().Use<PostsDB>();
...
In my HomeController I am
private IPostDataSource _db;
public HomeController(IAdsDataSource db)
{
_db = db;
}
I can retrieve all the posts by _db.Posts
public ActionResult Index()
{
var Posts= _db.Posts;
ViewBag.Posts = Posts;
return View();
}
The problem is what query should I write in order to retrieve all posts from a specific categrory
If a category has a collection of Posts, then Post entity should have a CategoryID property. You can query base on that CategoryID.
Otherwise you can query the category and retrieve the corresponding list of Posts:
var cat = _db.Categories.Where(a => a.Id == catId).FirstOrDefault();
if(cat != null)
ViewBag.Posts = cat.Posts;
return View();

Resources