Connection lost with sdf file in a mvc project - asp.net-mvc

I´m starting to learn mvc with the tutorial MVC Music Store v3.0b. The code download from mvcmusicstore.codeplex.com Works fine. Now I´m trying the same example but using my own model.
My connectionstring in my web.config file is:
<connectionStrings>
<add name="PlanetStampEntities"
connectionString="Data Source=|DataDirectory|MvcPlanetStamp.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
The problem is that I can´t access to data stored in the class SampleData.cs under Models folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPlanetStamp.Models;
namespace MvcPlanetStamp.Controllers
{
public class StoreController : Controller
{
PlanetStampEntities storeDB = new PlanetStampEntities();
public ActionResult Index()
{
var tematicas = storeDB.Tematicas.ToList();
return View(tematicas);
}
}
}
var tematicas never get results. But I have records in my class SampleData.cs
public class SampleData : DropCreateDatabaseIfModelChanges<PlanetStampEntities>
{
protected override void Seed(PlanetStampEntities context)
{
var tematicas = new List<Tematica>
{
new Tematica { Nombre = "Modernismo" },
new Tematica { Nombre = "Alhambra" },
new Tematica { Nombre = "Hollywood" },
new Tematica { Nombre = "Dibujos" },
new Tematica { Nombre = "Montañas" },
};
----
Finally, the code for my class PlanetStampsEntities.cs is:
using System.Data.Entity;
namespace MvcPlanetStamp.Models
{
public class PlanetStampEntities : DbContext
{
public DbSet<Sello> Sellos { get; set; }
public DbSet<Tematica> Tematicas { get; set; }
public DbSet<Pais> Paises { get; set; }
}
}
Table Selloes in the tree seems wrong. My class is Sello.cs. Where this name Selloes could be created?
Thank you

Change your table name in .sdf file from Selloes to Sello

Related

Using a controller with WEB API Routing

In my project (Asp.net MVC), I want to use DevExtreme GridView to display my data. I've used code first to create databases and tables. In the project, I have a model with the name of Member. I did right click on the Controller folder and select Add->Controller->DevExtreme Web API Controller with actions, using Entity Framework. In the wizard, I selected my database context and model and determine my controller name (MembersController) and then clicked Add. So in the Views folder, I created a folder with name Members and inside it, I added a view with name Index. (I don't know what exactly name must be for view, you suppose Index). In the index view, I used the wizard to add a DevExtreme GridView (Right-click on the view context and click on Insert A DevExtreme Control Here. In the wizard, I selected GridView as control and DatabaseContext, Member model and Members controller. You can see all of my codes in the below:
Member Mode:
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication2.Models
{
public class Member
{
#region Ctor
public Member()
{
}
#endregion
#region Properties
[Key]
public int MemberID { get; set; }
[Required(ErrorMessage ="*")]
public string FirstName { get; set; }
[Required(ErrorMessage = "*")]
public string LastName { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
[Required(ErrorMessage = "*")]
public string NID { get; set; }
[Required(ErrorMessage = "*")]
public string MID { get; set; }
[Required(ErrorMessage = "*")]
public string SalaryID { get; set; }
#endregion
}
}
Controller:
[Route("api/Members/{action}", Name = "MembersApi")]
public class MembersController : ApiController
{
private ApplicationDbContext _context = new ApplicationDbContext();
[HttpGet]
public HttpResponseMessage Get(DataSourceLoadOptions loadOptions) {
var members = _context.Members.Select(i => new {
i.MemberID,
i.FirstName,
i.LastName,
i.Phone,
i.Mobile,
i.NID,
i.MID,
i.SalaryID
});
return Request.CreateResponse(DataSourceLoader.Load(members, loadOptions));
}
[HttpPost]
public HttpResponseMessage Post(FormDataCollection form) {
var model = new Member();
var values = JsonConvert.DeserializeObject<IDictionary>(form.Get("values"));
PopulateModel(model, values);
Validate(model);
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, GetFullErrorMessage(ModelState));
var result = _context.Members.Add(model);
_context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.Created, result.MemberID);
}
[HttpPut]
public HttpResponseMessage Put(FormDataCollection form) {
var key = Convert.ToInt32(form.Get("key"));
var model = _context.Members.FirstOrDefault(item => item.MemberID == key);
if(model == null)
return Request.CreateResponse(HttpStatusCode.Conflict, "Member not found");
var values = JsonConvert.DeserializeObject<IDictionary>(form.Get("values"));
PopulateModel(model, values);
Validate(model);
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, GetFullErrorMessage(ModelState));
_context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
[HttpDelete]
public void Delete(FormDataCollection form) {
var key = Convert.ToInt32(form.Get("key"));
var model = _context.Members.FirstOrDefault(item => item.MemberID == key);
_context.Members.Remove(model);
_context.SaveChanges();
}
private void PopulateModel(Member model, IDictionary values) {
string MEMBER_ID = nameof(Member.MemberID);
string FIRST_NAME = nameof(Member.FirstName);
string LAST_NAME = nameof(Member.LastName);
string PHONE = nameof(Member.Phone);
string MOBILE = nameof(Member.Mobile);
string NID = nameof(Member.NID);
string MID = nameof(Member.MID);
string SALARY_ID = nameof(Member.SalaryID);
if(values.Contains(MEMBER_ID)) {
model.MemberID = Convert.ToInt32(values[MEMBER_ID]);
}
if(values.Contains(FIRST_NAME)) {
model.FirstName = Convert.ToString(values[FIRST_NAME]);
}
if(values.Contains(LAST_NAME)) {
model.LastName = Convert.ToString(values[LAST_NAME]);
}
if(values.Contains(PHONE)) {
model.Phone = Convert.ToString(values[PHONE]);
}
if(values.Contains(MOBILE)) {
model.Mobile = Convert.ToString(values[MOBILE]);
}
if(values.Contains(NID)) {
model.NID = Convert.ToString(values[NID]);
}
if(values.Contains(MID)) {
model.MID = Convert.ToString(values[MID]);
}
if(values.Contains(SALARY_ID)) {
model.SalaryID = Convert.ToString(values[SALARY_ID]);
}
}
private string GetFullErrorMessage(ModelStateDictionary modelState) {
var messages = new List<string>();
foreach(var entry in modelState) {
foreach(var error in entry.Value.Errors)
messages.Add(error.ErrorMessage);
}
return String.Join(" ", messages);
}
protected override void Dispose(bool disposing) {
if (disposing) {
_context.Dispose();
}
base.Dispose(disposing);
}
}
View:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#(Html.DevExtreme().DataGrid<WebApplication2.Models.Member>()
.DataSource(ds => ds.WebApi()
.RouteName("MembersApi")
.LoadAction("Get")
.InsertAction("Post")
.UpdateAction("Put")
.DeleteAction("Delete")
.Key("MemberID")
)
.RemoteOperations(true)
.Columns(columns => {
columns.AddFor(m => m.MemberID);
columns.AddFor(m => m.FirstName);
columns.AddFor(m => m.LastName);
columns.AddFor(m => m.Phone);
columns.AddFor(m => m.Mobile);
columns.AddFor(m => m.NID);
columns.AddFor(m => m.MID);
columns.AddFor(m => m.SalaryID);
})
.Editing(e => e
.AllowAdding(true)
.AllowUpdating(true)
.AllowDeleting(true)
)
)
WebApiConfig.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApplication2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// WebAPI when dealing with JSON & JavaScript!
// Setup json serialization to serialize classes to camel (std. Json format)
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
}
Global.asax.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace WebApplication2
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
In addition I've installed all requirements for this project according this link.
But when I try to show View with https://localhost:44328/Members/index RUL, I get this error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Members/index
I'v tried a lot way to correct my wrong but I couldn't find solution. I almost read all of documents about routing (mvc and web api), but after about 5 days I still couldn't to solve it.
Thanks a lot for answer me.
The thing is as far as I can tell, one of the reasons you are receiving a 404 is because you don't seem to be adding your parameter anywhere. Aside from that your 'DataSourceLoadOptions loadOptions' shouldn't be used as a parameter because it is probably too complex. Shouldn't you create a service which retrieves your loadOptions instead of you giving it along?
If you want all members without giving information then you should do exactly that. Not give the request some metadata it doesn't know about along for the ride.
I suggest you do the following:
Create an API which does not need metadata like how to get a datasource. Things such as Members.LastName are acceptable
Make sure you create a service which is responsible for getting your data in the first place. This means also removing all that extra code in your controller and placing it in a more suitable location.
Keep your classes clean and simple. Your controller now has too many responsibilities.
Hopefully this'll help. If you try your API GET Method as is without the 'DataSourceLoadOptions loadOptions' parameter, then your API will not return 404.
Since you didn't put in your ajax call url, I'm going to have to work with this
Requested URL: /Members/index
This is a problem, your webApi default route requires your URL to be prepended with /api/
So something like this should work /api/Members, so you can remove the Index part of that URL as the request type will handle which Action is executed ie HTTPGet/HTTPPost
EDIT: Use this as your route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Members" id = RouteParameter.Optional }
);

Is there get method which not found while run web api service

I'm creating a web api controller and implement ([HttpGet])parameterized get method with datatype class but when I run this its show 404 Not Found.
When i am implementing normal datatype like string or int its show me the answer or datatype like List still it's giving me answer but when I directly declare datatype as class like Student its show 404 not found error. I don't know why it's so. I am trying to learn web api with mvc please help me.
I am creating one simple class Student and one studentapicontroller.In my api controller, I create get method with datatype class and for testing purpose i make other get method with different datatype
Student.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace epay.Models
{
public class student
{
public int id { get; set; }
public string name { get; set; }
}
}
studentapiController :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using epay.Models;
namespace epay.Controllers
{
public class studentapiController : ApiController
{
// GET api/studentapi
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/studentapi/5
{
return "value";
}
// POST api/studentapi
public void Post([FromBody]string value)
{
}
// PUT api/studentapi/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/studentapi/5
public void Delete(int id)
{
}
//POST api/studentapi/
[HttpGet]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
//GET api/studentapi/getstud
[HttpGet]
public List<student> getstud()
{
List<student> lst = new List<student>();
student st = new student();
st.name = "manlai";
st.id = 5;
lst.Add(st);
return lst;
}
}
}
I just want getdetails result or how to do if I want my method datatype as a class and I am passing parameter with my get method how to do this
Make getdetails route like below because it is conflicting with get
[HttpGet("getdetails")]
public student getdetails(int id, string na)
{
student st = new student();
st.id = id;
st.name = na;
return st;
}
you can call route something like this with querystring /studentapi/getdetails?id=1&na=test

Entity Framework 6 Code First Fail

I'm new in Entity Framework and I'm testing a simple application but it doesn't work.
Let me explain step by setp what I'm doing:
1- Create a Console App using VS 2013 Express
2- Include a reference to EF6 by Nuget
3- Create the Student Class:
namespace CSharp_CodeFirst
{
public class Student
{
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
}
}
4- Create the context class
using System.Data.Entity;
namespace CSharp_CodeFirst
{
public class StudentDataContext : DbContext
{
public StudentDataContext() : base()
{
}
public DbSet<Student> Students;
}
}
5- Create the code in Program.cs
namespace CSharp_CodeFirst
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new StudentDataContext())
{
Student stud = new Student() { name = "New Student", email="test#test.com" , Id=1 };
ctx.Students.Add(stud);
ctx.SaveChanges();
}
}
}
}
6- Build without errors
7- When I execute the project I get the error :
An unhandled exception of type 'System.NullReferenceException' occurred in CSharp_CodeFirst.exe
Object reference not set to an instance of an object.
The error occur in this line of code : ctx.Students.Add(stud);
I'm using the sample in this site : http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx
I Feel Like I'm Forgetting Something, but What ???
Thanks

MVC update model with Code-Migrations

I am making my project in MVC4, where i am using my Code first approach. i need to update my model
i have a following property which needs to be update , how can i achieve this
public class ContactForm
{
public char Phone { get; set; }
}
public class ConContext : DbContext
{
public DbSet<ContactForm> ContactForms { get; set; }
}
}
i want to update Phone propery to
public char Phone { get; set; }
thnx in advance, i have installed migrations to my projet already
My configuration.cs
namespace MyCRM.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<MyCRM.Models.ConContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(MyCRM.Models.ConContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
The normal flow with EF code-first is too first update the model (a C# file) :
public class ContactForm
{
public string Phone { get; set; } //previously, this was let's say of type int
}
Then, you build your project and after that in the Package Manager Console, you have to call Add-Migration with some label (in order to rollback changes later if needed) :
Add-Migration Phone
This will add to your solution a file named like this 201409xxxxxxxx_Phone under the directory Migrations.
Then you have to put the changes to your database which can be done with the command (always in the console) :
Update-Database
Then, you should be done : the property Phone is of type string everywhere.

ASP.NET My Music Store

I need help Sir, newbie in MVC, I would like to ask why I can't find
the store DB even it is declared at the bottom.
The "storeDB" does not exist in the current context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMusicStore.Models;
namespace MyMusicStore.Controllers
{
public class StoreController : Controller
{
//
// GET: /Store/
public ActionResult Index()
{
var genres = storeDB.Genres.ToList();
return View(genres);
}
public ActionResult Browse(string genre)
{
var newGenre = new Genre { Name = genre };
return View (newGenre);
}
public ActionResult Details(int id)
{
var album = new Album { Title = "Album" + id };
return View(album);
}
public class StoreController : Controller
{
MusicStoreEntities storeDB = new MusicStoreEntities();
}
}
}
Inside of the class StoreController, you declare StoreController a second time, and declare the variable inside that. What you've made is what's called an 'inner class', and the inner class is DIFFERENT from the outer class even though it appears to have the same name, it is brand new.
So you meant to do this instead:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMusicStore.Models;
namespace MyMusicStore.Controllers
{
public class StoreController : Controller
{
//
// GET: /Store/
public ActionResult Index()
{
var genres = storeDB.Genres.ToList();
return View(genres);
}
public ActionResult Browse(string genre)
{
var newGenre = new Genre { Name = genre };
return View (newGenre);
}
public ActionResult Details(int id)
{
var album = new Album { Title = "Album" + id };
return View(album);
}
MusicStoreEntities storeDB = new MusicStoreEntities();
}
}

Resources