When I tried to add data into the database this exception arise. I cant figure out where the problem exist. please help me to find out the where the problem is.
[Table("actors_tb")]
public class Actors
{
[Key]
public int id { get; set; }
public string name { get; set; }
public string sex { get; set; }
public DateTime dob { get; set; }
public string bio { get; set; }
}
This is my DbContext Class
public class CinemaDbContext:DbContext
{
public CinemaDbContext() : base("DefaultConnection")
{
}
public DbSet<Actors> actores { get; set; }
public DbSet<Producers> Producer { get; set; }
public DbSet<movie> movies { get; set; }
}
This is my controller
public ActionResult Actors()
{
return View();
}
[HttpPost]
public ActionResult Actors(Actors actors)
{
Db.actores.Add(actors);
Db.SaveChanges();
return View();
}
Related
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();
}
I hate these kind of errors.
I have an ASP.NET Core MVC form. When I submit the form I get the dreaded "No parameterless constructor defined for this object." error.
I can't seem to hit anything in the debugger to help me find where I have went wrong.
My controller:
using Brand.Extensions;
using Brand.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Brand.Controllers
{
public class ContentController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Upload()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upload(UploadedContentModel uploadedContentModel, FormCollection formCollection, IFormFileCollection uploadedFiles)
{
ContentExtensions contentExtensions = new ContentExtensions();
FileExtensions fileExtensions = new FileExtensions();
FileModel file = new FileModel();
file = fileExtensions.GetFileModel(uploadedFiles["File"]);
uploadedContentModel.File = fileExtensions.UploadFile(file).ID;
FileModel thumbnail = new FileModel();
thumbnail = fileExtensions.GetFileModel(uploadedFiles["Thumbnail"]);
uploadedContentModel.Thumbnail = fileExtensions.UploadFile(thumbnail).ID;
uploadedContentModel.ID = contentExtensions.UploadContent(uploadedContentModel).ID;
return View();
}
}
}
My model:
public class UploadedContentModel
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Guid File { get; set; }
public Guid Thumbnail { get; set; }
public string ContentType { get; set; }
public string Solutions { get; set; }
public string Industries { get; set; }
public string AdditionalTags { get; set; }
public DateTime Publish { get; set; }
public DateTime Expire { get; set; }
public string AuthorizedRoles { get; set; }
public string Author { get; set; }
public DateTime Created { get; set; }
}
Relatively new to MVC and can't figure out how to pass data from multiple models into a single view. I know I need to use a view model, but I can't figure out what to do in the controller.
Models:
public class Child
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ChartNumber { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip Code")]
public int ZipCode { get; set; }
public string Ethnicity { get; set; }
public string Referral { get; set; }
[Display(Name = "Recommended Re-evaluation")]
public bool ReEval { get; set; }
[Display(Name = "Hearing Aid Candidate")]
public bool HaCandidate { get; set; }
[Display(Name = "Fit With Hearing Aid")]
public bool FitHa { get; set; }
public virtual List<ChildEval> ChildEvals { get; set; }
}
public class ChildEval
{
[Key]
public int ChildEvalId { get; set; }
public DateTime Date { get; set; }
public int PtaRight { get; set; }
public int PtaLeft { get; set; }
public int UnaidedSiiRight { get; set; }
public int UnaidedSiiLeft { get; set; }
public int AidedSiiRight { get; set; }
public int AidedSiiLeft { get; set; }
public int ChartNumber { get; set; }
public virtual Child Child { get; set; }
}
}
DbContext
public class UnitedContext : DbContext
{
public UnitedContext() : base("name=UnitedContext")
{
}
public System.Data.Entity.DbSet<United.Models.Child> Children { get; set; }
public System.Data.Entity.DbSet<United.Models.ChildEval> ChildEvals { get; set; }
}
ViewModel:
public class ChildViewModel
{
public class Child
{
public string FirstName { get; set; }
}
public class ChildEval
{
public int PtaRight { get; set; }
}
}
ViewModelController? :
public class ViewModelController : Controller
{
//
// GET: /ViewModel/
public ActionResult Index()
{
return View();
}
}
}
I'm stuck on how to create the controller for the viewmodel and how to actually get the data into the view. Any help would be greatly appreciated!
Don't have a controller called ViewModelController. Controller is the handler between database and the view. Therefore the name of the controller should tell the programmer what kind of data the controller is controlling. By default, it also indicates the subsite you are in your web application ( ViewModelController would yield http://mysite/ViewModel/ ).
Since you are handling children, I'm calling it ChildrenController for now.
Generally a good idea is to wrap your 2 models into one viewmodel and work with that. In this case Model != ViewModel, model is the database model of the entity while ViewModel is the one that's passed to/from the view.
public class Child
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class SomeOtherModel
{
public int ID { get; set; }
public int SomeInteger { get; set; }
public int SomeOtherInteger { get; set; }
}
public class ChildViewModel
{
public Child Child { get; set; }
public SomeOtherModel SomeOtherModel { get; set; }
public ChildViewModel(Child child, SomeOtherModel s)
{
Child = child;
SomeOtherModel = s;
}
}
In your controller
public class ChildrenController : Controller
{
//
// GET: /Children/
public ActionResult Index()
{
Child child = /*Fetch the child from database*/;
SomeOtherModel someOther = = /*Fetch something else from database*/;
ChildViewModel model = new ChildViewModel(child,someOther);
return View(model);
}
}
View:
#model ChildViewModel
#Html.EditorFor(model => model.Child.FirstName)
#Html.EditorFor(model => model.Child.LastName)
First of all, I'm new to MVC.
I want to display the properties of the JSON response in a html view.
For example, i want to get the number of page likes from the JSON response and display just the number of likes on a page.
Any help is much appreciated :)
//
// GET: /Facebook/
public ActionResult Index()
{
var json = new WebClient().DownloadString("https://graph.facebook.com/google");
JsonConvert.DeserializeObject<RootObject>(json);
return view();
}
public class CategoryList
{
public string id { get; set; }
public string name { get; set; }
}
public class Location
{
public string street { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string zip { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
}
public class Cover
{
public string cover_id { get; set; }
public string source { get; set; }
public int offset_y { get; set; }
public int offset_x { get; set; }
}
public class RootObject
{
public string about { get; set; }
public string awards { get; set; }
public string category { get; set; }
public List<CategoryList> category_list { get; set; }
public int checkins { get; set; }
public string company_overview { get; set; }
public string description { get; set; }
public string founded { get; set; }
public bool is_published { get; set; }
public Location location { get; set; }
public string mission { get; set; }
public string phone { get; set; }
public string products { get; set; }
public int talking_about_count { get; set; }
public string username { get; set; }
public string website { get; set; }
public int were_here_count { get; set; }
public string id { get; set; }
public string name { get; set; }
public string link { get; set; }
public int likes { get; set; }
public Cover cover { get; set; }
}
}
}
Your action should pass the object to the view:
public ActionResult Index()
{
var json = new WebClient().DownloadString("https://graph.facebook.com/google");
var root=JsonConvert.DeserializeObject<RootObject>(json);
return view(root);
}
and then in your view you can show whichever property you want:
#Model RootObject
<html>
<head>
<title>Showing properties</title>
</head>
<body>
#Model.likes likes.
</body>
</html>
This is if you use the Razor syntax.
you're missing
return view(root);
You should pass the object back to view to use it.
you can use JsonResult in mvc 4,
public JsonResult ReturnSomeJson()
{
JsonResult result = new JsonResult();
//Assign some json value to result.
//Allow get is used to get the value in view.
return view(result,AllowGet.True);
}
I was looking for a similar solution and I found it to be a bit different:
[HttpGet]
public JsonResult Index() {
// your code
return Json("some result string or value", JsonRequestBehavior.AllowGet);
}
This outputs "some result string or value" in your browser when you call this action directly.
Assuming this is a normal action inside a controller that
inherits from Controller class.
Should T be a for example Customer or CustomerViewModel ?
The annotations bound to Mvc namespace are on the ListViewModel so actually I could pass the Customer object. What do you think?
public class ListViewModel<T>
{
[Required(ErrorMessage="No item selected.")]
public int[] SelectedIds { get; set; }
public IEnumerable<T> DisplayList { get; set; }
}
UPDATE
[HttpGet]
public ActionResult Open()
{
IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();
OpenTestplanListViewModel viewModel = new OpenTestplanListViewModel(testplans);
return PartialView(viewModel);
}
public class OpenTestplanListViewModel
{
public OpenTestplanListViewModel(IEnumerable<Testplan> testplans)
{
var testplanViewModels = testplans.Select(t => new TestplanViewModel
{
Name = string.Format("{0}-{1}-{2}-{3}", t.Release.Name, t.Template.Name, t.CreatedAt, t.CreatedBy),
TestplanId = t.TestplanId,
});
DisplayList = testplanViewModels;
}
[Required(ErrorMessage = "No item selected.")]
public int[] SelectedIds { get; set; }
public string Name { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; private set; }
}
public class TestplanViewModel
{
public int TestplanId { get; set; }
public string Name { get; set; }
}
public class Testplan
{
public int TestplanId { get; set; }
public int TemplateId { get; set; }
public int ReleaseId { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public Template Template { get; set; }
public Release Release { get; set; }
}
T should ideally be a view model. Having a view model referencing domain models is some kind of a hybrid view model, not a real one. But if you think that in this specific case the domain model will be exactly the same as the view model then you could keep it as well.