MVC4 EF5 entity property not updating on SaveChanges() - asp.net

I've been reading through lots of articles trying to learn MVC4, but I'm stumped as to why my entity is not getting updated to database.
I've been trying to modify the MVC4 VS2012 Internet template.
So, here's the Controller action:
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
STUDENTI_STRANIERI_MASTER_REG st2 = studente;
st2.ESITO = 1;
//studente.ESITO = 1;
var statos = context.Entry(studente).State;
Console.WriteLine("Before DetectChanges: {0}",statos);
//context.ChangeTracker.DetectChanges();
context.Entry(studente).State = EntityState.Modified;
context.Entry(studente).CurrentValues.SetValues(st2);
// var tracked = context.ChangeTracker.Entries();
context.Entry(studente).Property( o => o.ESITO ).IsModified = true;
TryUpdateModel(studente);
context.SaveChanges();
Console.WriteLine("After DetectChanges: {0}",statos);
return RedirectToAction("PrivateIndex");
}
}
The aim is just to update one property, ESITO and set it to 1. Currently its value is 2.
This is the model:
namespace MvcStudenti2.Models
{
using System;
using System.Collections.Generic;
public partial class STUDENTI_STRANIERI_MASTER_REG
{
public long ID_PERSONA { get; set; }
public string COGNOME { get; set; }
public string NOME { get; set; }
public string SESSO { get; set; }
public System.DateTime DATA_NASCITA { get; set; }
public long ID_STATO_NASCITA { get; set; }
public string LUOGO_NASCITA_ESTERO { get; set; }
public string CODICE_FISCALE { get; set; }
public string TITOLO_POSSEDUTO { get; set; }
public Nullable<short> DURATA_TITOLO { get; set; }
public string VOTAZIONE { get; set; }
public string UNI_PROVENIENZA { get; set; }
public long ID_STATO_UNI { get; set; }
public string CERT_LINGUISTICA { get; set; }
public string CERT_PUNTEGGIO { get; set; }
public string NOTE { get; set; }
public System.DateTime DATA_RICHIESTA { get; set; }
public short ESITO { get; set; }
public string CDS_COD { get; set; }
public string EMAIL { get; set; }
public string NUMERO_TELEFONO { get; set; }
public string INDIRIZZO { get; set; }
public string CAP_INDIRIZZO { get; set; }
public string CITTA { get; set; }
public long ID_STATO_INDIRIZZO { get; set; }
public string DESCRIZIONE_CIT_NAZ { get; set; }
public Nullable<System.DateTime> DATA_COMPLETAMENTO_ATTESO { get; set; }
public Nullable<System.DateTime> ANNO_COMPLETAMENTO { get; set; }
public Nullable<short> DURATA_CORSO_COMPLETATO { get; set; }
public decimal GPA { get; set; }
public string ALTRI_TITOLI { get; set; }
public string MADRELINGUA { get; set; }
public Nullable<short> CERT_TOEFL_PUNT { get; set; }
public string CERT_FIRSTCERT_GRADE { get; set; }
public Nullable<short> CERT_FIRSTCERT_PUNT { get; set; }
public byte[] FILE_CV { get; set; }
public byte[] FILE_CARRIERA { get; set; }
public byte[] FILE_CERT_LINGUA { get; set; }
public byte[] FILE_DOC_IDENTITA { get; set; }
public string PWD { get; set; }
public string FILE_CV_NOME { get; set; }
public string FILE_CARRIERA_NOME { get; set; }
public string FILE_CERT_LINGUA_NOME { get; set; }
public string FILE_DOC_IDENTITA_NOME { get; set; }
public string FILE_CV_TIPO { get; set; }
public string FILE_CARRIERA_TIPO { get; set; }
public string FILE_CERT_LINGUA_TIPO { get; set; }
public string FILE_DOC_IDENTITA_TIPO { get; set; }
public Nullable<short> STATO { get; set; }
public Nullable<short> VALUTATO { get; set; }
public Nullable<short> ARCHIVIATO { get; set; }
public string CDS_COD_2 { get; set; }
public Nullable<short> MAIL_INVIATA { get; set; }
public string LINK_ULTIMO_CORSO { get; set; }
public Nullable<short> ATTIVO { get; set; }
public byte[] FILE_LETTERA_ACCETTAZIONE { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_NOME { get; set; }
public string FILE_LETTERA_ACCETTAZIONE_TIPO { get; set; }
}
}
Everywhere I read I find that SaveChanges() should be enough, possibly after the EntityState.Modified.
I can correctly edit the entity, if I pass the whole entity to the Action, but in this case the Approve view is a built on a Detail template, so I don't have anything to POST from it (and I'd prefer not to: I could insert a hidden field and post just that, but I'm trying to update a single filed from code, and I'm not sure if the whole entity would get updated or overwritten ).
statos goes to "modified", if I understand correctly, because I have done a query on the entity.
Another thing I don't understand is why ESITO gets update -also- in studente, but then reverts to "2" after SaveChanges().
Are property changes being detected? I've wrapped every Action in a using block, as suggested elsewhere, so not to have multiple contextx/instances around.
Could anyone please point me to what I'm doing wrong? The code above is probably over-redundant, but I've been trying everything I have found on SO.
Thanks, everyone.

The following is all that is required to change the ESITO property.
[HttpPost, ActionName("Approve")]
[Authorize]
public ActionResult ApproveConfirmed(long id)
{
using (StudentiContext context = new StudentiContext())
{
// context.Configuration.AutoDetectChangesEnabled = false;
var studente = (from d in context.STUDENTI_STRANIERI_MASTER_REG
where d.ID_PERSONA == id
select d).Single();
studente.ESITO = 1;
context.SaveChanges();
return RedirectToAction("PrivateIndex");
}
}

Related

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

Trying to recreate a solution given for a question, need a little assistance

Trying to recreate a solution given for ASP.NET MVC - Taking search criteria as input, and displaying the results, in the same View?, but not sure where to find the querymanager that derloopkat uses in his example.
[HttpPost]
public ActionResult Query(FormQueryModel model)
{
var queryManager = new QueryManager(model);
model.QueryResults = queryManager.GetResults();
return View(model);
}
My ViewModels
public class PartRequestInfoSearch
{
public int? Building { get; set; }
public int? PartType { get; set; }
public int? PartStatus { get; set; }
public Nullable<System.DateTime> tmpStartDate { get; set; }
public Nullable<System.DateTime> tmpEndDate { get; set; }
public int PageSize { get; set; }
public List<RequestedPartInfo> RequestedPartInfos { get; set; }
public PartRequestInfoSearch()
{
this.RequestedPartInfos = new List<RequestedPartInfo>();
}
}
}
public class RequestedPartInfo
{
public int idPartRequest { get; set; }
public string Building { get; set; }
public string RequestNumber { get; set; }
public string PartNumber { get; set; }
public string VendorPartNumber { get; set; }
public string PartDescription { get; set; }
public int StockQTY { get; set; }
public int RequestQTY { get; set; }
public int ShippedQTY { get; set; }
public string PartStatus { get; set; }
}

Edit multiple related tables on ASP.net MVC w/Entity Framework 6

I'll open with the statement that I am very new to .net and MVC so please bear with me. I'm using Visual Studio 2013 and learning as I go.
Essentially - I have a .net MVC database-first project connected to a SQL db. I used scaffolding to create 4 models -
(Survey_Header_Response) - base survey information, identifies which survey a respondent gets
(Survey_Question) holds a unique list of the questions for all surveys and provides the actual question text,
(Survey_Response) lists of all the questions in the survey identified in (Survey_Response_Header) and will hold the value of each answer on post,
(Response_Values) - holds a list of possible responses for each of the different questions in each survey . Information on these is as follows:
Note - models are scaffolded, so even if I change them, they change back on db update.
Survey_Response_Header model:
public partial class Survey_Response
{
public Survey_Response()
{
this.Response_Values = new HashSet<Response_Values>();
}
public int Survey_Response_RecID { get; set; }
public int Survey_RecID { get; set; }
public int Survey_Question_RecID { get; set; }
public string Response { get; set; }
public Nullable<System.DateTime> Date_Responded { get; set; }
public int Contact_RecID { get; set; }
public int Company_RecID { get; set; }
public System.DateTime Date_Sent { get; set; }
public bool Responded { get; set; }
public string Survey_Qtr { get; set; }
public System.Guid Respondent_ID { get; set; }
public virtual Survey_Detail Survey_Detail { get; set; }
public virtual Survey_Question Survey_Question { get; set; }
public virtual ICollection<Response_Values> Response_Values { get; set; }
public virtual Survey_Response_Header Survey_Response_Header { get; set; }
}
Survey_Question:
public partial class Survey_Question
{
public Survey_Question()
{
this.Survey_Cat_SubCat = new HashSet<Survey_Cat_SubCat>();
this.Survey_Detail = new HashSet<Survey_Detail>();
this.Response_Values = new HashSet<Response_Values>();
this.Survey_Response = new HashSet<Survey_Response>();
}
public int Survey_Question_RecID { get; set; }
public string Question { get; set; }
public bool Inactive_Flag { get; set; }
public System.DateTime Date_Created { get; set; }
public string Created_By { get; set; }
public System.DateTime Date_Updated { get; set; }
public string Updated_By { get; set; }
public virtual ICollection<Survey_Cat_SubCat> Survey_Cat_SubCat { get; set; }
public virtual ICollection<Survey_Detail> Survey_Detail { get; set; }
public virtual ICollection<Response_Values> Response_Values { get; set; }
public virtual ICollection<Survey_Response> Survey_Response { get; set; }
}
Survey Response:
public Survey_Response()
{
this.Response_Values = new HashSet<Response_Values>();
}
public int Survey_Response_RecID { get; set; }
public int Survey_RecID { get; set; }
public int Survey_Question_RecID { get; set; }
public string Response { get; set; }
public Nullable<System.DateTime> Date_Responded { get; set; }
public int Contact_RecID { get; set; }
public int Company_RecID { get; set; }
public System.DateTime Date_Sent { get; set; }
public bool Responded { get; set; }
public string Survey_Qtr { get; set; }
public System.Guid Respondent_ID { get; set; }
public virtual Survey_Detail Survey_Detail { get; set; }
public virtual Survey_Question Survey_Question { get; set; }
public virtual ICollection<Response_Values> Response_Values { get; set; }
public virtual Survey_Response_Header Survey_Response_Header { get; set; }
}
Response_Values:
public partial class Response_Values
{
public Response_Values()
{
this.Survey_Response = new HashSet<Survey_Response>();
}
public int Survey_RecID { get; set; }
public int Survey_Question_RecID { get; set; }
public int Value { get; set; }
public int Question_Type_RecID { get; set; }
public string Value_Label { get; set; }
public Nullable<System.DateTime> Date_Created { get; set; }
public string Created_By { get; set; }
public Nullable<System.DateTime> Date_Updated { get; set; }
public string Updated_By { get; set; }
public int Response_Value_RecID { get; set; }
public virtual Question_Type Question_Type { get; set; }
public virtual Survey_Question Survey_Question { get; set; }
public virtual Survey Survey { get; set; }
public virtual Survey_Detail Survey_Detail { get; set; }
public virtual ICollection<Survey_Response> Survey_Response { get; set; }
}
}
There is a many-to-many relationship between the Response_Values & Survey_Response tables through the use of a pure-join table not shown here.
ViewModels: (See edit below)
ResponseData (intended to hold Survey_Response data and reference related tables)
I apologize for the length of this question - I'm new at this so my coding is probably messy and my explanation long. Any help provided is much appreciated and will help me learn!
Edit:
Thanks for your reply. I understand where you're coming from, and I've attempted to build the controller but when I try to populate the ResponseData viewModel that contains the ICollection Survey_Response with data, I get an error "Cannot implicitly convert type 'System.Collections.Generic.List CustomerExperienceSurveyWeb.Models.Survey_Response' to 'System.Collections.Generic.ICollection CustomerExperienceSurveyWeb.ViewModels.SurveyResponseVM'. An explicit conversion exists (are you missing a cast?)"
Here's the relevant part of my controller code:
public ActionResult Edit(Guid id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//Survey_Response_Header survey = db.Survey_Response_Header.Find(id);
var survey = db.Survey_Response_Header
.Include(i => i.Survey_Response)
.Where(i => i.Responded_ID == id)
.Select(i => new
{
ViewModel = new ResponseData
{
Responded_ID = i.Responded_ID,
Company_RecID = i.Company_RecID,
Contact = i.Contact,
Contact_RecID = i.Contact_RecID,
Date_Responsed = i.Date_Responsed,
Date_Sent = i.Date_Sent,
Responded = i.Responded,
Survey_Qtr = i.Survey_Qtr,
Survey_RecID = i.Survey_RecID,
SurveyResponse = i.Survey_Response.ToList() <<--- This is where the error shows
}
})
.Single();
Updated ResponseData viewModel:
public partial class ResponseData
{
public ResponseData()
{
this.SurveyResponse = new List<SurveyResponseVM>();
}
public System.Guid Responded_ID { get; set; }
public int Survey_RecID { get; set; }
public System.DateTime Date_Sent { get; set; }
public Nullable<System.DateTime> Date_Responsed { get; set; }
public bool Responded { get; set; }
public int Contact_RecID { get; set; }
public int Company_RecID { get; set; }
public string Survey_Qtr { get; set; }
public virtual Contact Contact { get; set; }
public virtual ICollection<SurveyResponseVM> SurveyResponse { get; set; }
}
Referenced SurveyResponseVM viewModel which is throwing the error:
public partial class SurveyResponseVM
{
public SurveyResponseVM()
{
this.Response_Values = new List<ValueData>();
}
public int Survey_Response_RecID { get; set; }
public int Survey_RecID { get; set; }
public int Survey_Question_RecID { get; set; }
public string Response { get; set; }
public Nullable<System.DateTime> Date_Responded { get; set; }
public int Contact_RecID { get; set; }
public int Company_RecID { get; set; }
public System.DateTime Date_Sent { get; set; }
public bool Responded { get; set; }
public string Survey_Qtr { get; set; }
public System.Guid Respondent_ID { get; set; }
public virtual Survey_Detail Survey_Detail { get; set; }
public virtual Survey_Question Survey_Question { get; set; }
public virtual ICollection<ValueData> Response_Values { get; set; }
public virtual Survey_Response_Header Survey_Response_Header { get; set; }
}
I know this means I'm not populating the ICollection part of the viewmodel correctly but I can't seem to figure out how it's supposed to be done. I've done days of research on the internet and I either don't know the right question to ask or I'm completely missing it. Any help you can give me is VERY appreciated!
So the controller is essentially responsible for populating a model and pass this model to a view for rendering, there doesn't need to correspond to a database table.
The way I normally tackle this is to look at what the function is being performed, in this case survey and create a SurveyController. In here you will have a bunch of actions that correspond to views that are responsible for retrieving the correct data from the database, populating a model and then passing the model to the view for rendering.
So if you wanted to display a list of questions, you may do something like this (apologies if this contains errors, no VS atm):
public class SurveyController : Controller
{
public ActionResult Index()
{
var model = new SurveyModel(); // This would contain any properties, like questions and their valid responses
return View(model);
}
}
public class SurveyModel
{
public IList<SurveyQuestionModel> Questions { get; set; }
}

EF6 MVC5 Setting a 1-1 Relationship

I have got my application up and running using Code first, I am trying to set a 1-1 relationship but when I update-database I get the error "SupplyPointId: Name: Each property name in a type must be unique. Property name 'SupplyPointId' is already defined."
I've tried removing the existing index constraint on SupplyPointAddress.SupplyPointId and that does not help. In the other table its the PK. Any comments really appreciated
public partial class SupplyPoint
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointId { get; set; }
public string SPID { get; set; }
public string SupplyPointName { get; set; }
public int SupplyPointTypeId { get; set; }
public DateTime SupplyPointEffectiveDateTime { get; set; }
public string GazateerRef { get; set; }
public virtual SupplyPointType SupplyPointType { get; set; }
//[ForeignKey("SupplyPointId")]
public virtual SupplyPointAddress SupplyPointAddress { get; set; }
}
public partial class SupplyPointAddress
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointAddressId { get; set; }
public int SupplyPointId { get; set; }
public string D5001_FreeDescriptor { get; set; }
public string D5002_SubBuildingName { get; set; }
public string D5003_BuildingName { get; set; }
public string D5004_BuildingNumber { get; set; }
public string D5005_DependentThoroughfareName { get; set; }
public string D5006_DependentThoroughfareDescriptor { get; set; }
public string D5007_ThoroughfareName { get; set; }
public string D5008_ThoroughfareDescriptor { get; set; }
public string D5009_DoubleDependentLocality { get; set; }
public string D5010_DependentLocality { get; set; }
public string D5011_PostTown { get; set; }
public string D5012_County { get; set; }
public string D5013_Postcode { get; set; }
public virtual SupplyPoint SupplyPoint { get; set; }
}
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPoint> SupplyPoints { get; set; }
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPointAddress> SupplyPointAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SupplyPointAddress>()
.HasOptional<SupplyPoint>(u => u.SupplyPoint)
.WithRequired(c => c.SupplyPointAddress).Map(p => p.MapKey("SupplyPointId"));
base.OnModelCreating(modelBuilder);
}
I moved the foreign key into SupplyPoint table so that the foreign key was being defined as SupplyPointAddressId in SupplyPoint. This worked and allows me to do SupplyPoint.SupplyPointAddress in resultant model
Since you're testing with a real DB. Use some of the
Database Initialization Strategies in Code-First:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
(Excerpt from this site)
It is pretty self explanatory.
If there's already a DB created, it just DROPs it.
Happy coding!

Retrieving twitter with json

I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);

Resources