Why am I getting a null pointer error in my view model ASP.NET MVC - sql

I am currently trying to read data from a database and send that data into a list so that I can display the data items in a list however, I am getting a null pointer error in my view near my foreach loop.
Controller:
public ActionResult Index()
{
try
{
connection.Open();
SqlCommand myCommand = new SqlCommand("SELECT Firstname, ExerciseName, PR_Weight FROM Users, Exercises, PR WHERE Exercises.ExerciseID = PR.ExerciseID AND PR.Username = Users.Username AND Firstname = 'Evan' ", connection);
SqlDataReader myReader = myCommand.ExecuteReader();
Globals.PRList.Clear();
while (myReader.Read())
{
PRViewModel pr = new PRViewModel();
pr.PR_ID = (int)myReader["PR_ID"];
pr.Username = myReader["Username"].ToString();
pr.ExerciseID = (int)myReader["ExerciseID"];
pr.PR_Weight = (int)myReader["PR_Weight"];
pr.PR_Date = myReader["PR_Date"].ToString();
pr.Exercises.exerciseID = (int)myReader["ExerciseID"];
pr.Exercises.exercsieName = myReader["ExerciseName"].ToString();
Globals.PRList.Add(pr);
}
}
catch (Exception err)
{
ViewBag.Status = 0;
}
finally
{
connection.Close();
}
return View(Globals.PRList);
}
Globals Class:
public static class Globals
{
public static string myConnection = #"Data Source=TYRONSSPEEDYBOY\SQLEXPRESS02;Initial Catalog=PR_Tracker_DB1;Integrated Security=True";
public static List<PRViewModel> PRList = new List<PRViewModel>();
}
Index View:
#foreach (PRViewModel pr in Model)
{
<tr>
<td>#pr.PR_ID</td>
<td>#pr.Username</td>
<td>#pr.ExerciseID</td>
<td>#pr.PR_Weight</td>
<td>#pr.PR_Date</td>
PRViewModel:
public PRViewModel()
{
Exercises = new ExerciseViewModel();
}
public int PR_ID { get; set; }
public string Username { get; set; }
public int ExerciseID { get; set; }
public int PR_Weight { get; set; }
public string PR_Date { get; set; }
public ExerciseViewModel Exercises { get; set; }

You select these fields from the database
SELECT Firstname, ExerciseName, PR_Weight
But you then go on to read out several values which don't exist in the reader (because they're not returned by your query)
PR_ID
Username
List item
ExerciseID
PR_Weight
PR_Date
ExerciseID
ExerciseName (only this one exists in your query)
Try correcting your query. Your code also assumes none of these fields are null in the database, if they are casting is likely to fail.

Related

RavenDb changes to Property (nullable) on Entity that is a class doesn't save

I have a class like this:
public class Content {
public string Id {get; set;} = "content/"
public ContentJob? Job {get; set;}
}
public class ContentJob {
public string JobId {get; set;} = string.Empty;
}
I can create the content and if the job is there it will persist. with Store/SaveChanges.
But what I can't do is update (or more accurately set) ContentJob on Content and have it detect that there was a change. (HasChange(instance) == false) and SaveChanges doesn't update the database.
Why? And how do I make it detect the change?
(incidentally I tried using C# 9 records in hopes that because it automatically does deep object equality that this would solve it and no, it doesn't)
I created an unit-test based on your question, and it works as expected.
[Fact]
public void ShouldWork()
{
using (var store = GetDocumentStore())
{
string id = string.Empty;
using (var session = store.OpenSession())
{
var c = new Content();
session.Store(c);
session.SaveChanges();
id = session.Advanced.GetDocumentId(c);
var entity = session.Load<Content>(id);
entity.Job = new ContentJob()
{
JobId = "123"
};
Assert.True(session.Advanced.HasChanged(entity));
session.SaveChanges();
}
Assert.False(string.IsNullOrEmpty(id));
using (var session = store.OpenSession())
{
var entity = session.Load<Content>(id);
Assert.NotNull(entity.Job);
Assert.Equal("123", entity.Job.JobId);
}
}
}
public class Content
{
public string Id { get; set; } = "content/";
public ContentJob? Job { get; set; }
}
public class ContentJob
{
public string JobId { get; set; } = string.Empty;
}

Entity Framework virtual ICollections

I'm new to .NET Core Entity Framework (code-first), but do daily progress.
I am now stuck on a probably small mistake and can't go on.
I have a class list that I am trying to fill and in there there is a virtual ICollection from another list, to be filled at the same time.
These are my classes
public class UgInfo
{
public Guid UserGroupId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UInfo> UInfo { get; set; }
}
public class UInfo
{
public string UserEmail { get; set; }
public string UserName { get; set; }
}
This is where the error occurs:
Invalid Initializer member declarator"
Code:
var ugList = (from ug in _context.Usergroups
join uug in _context.UserUsergroup on ug.UserGroupId equals uug.UsergroupId
join u in _context.Users on uug.UserId equals u.UserId
select new UgInfo
{
UserGroupId = uug.UsergroupId,
Description = ug.Description,
Name = ug.Name,
new UInfo //Error
{
UserName = u.UserName,
UserEmail = u.Email
}
}).ToList();
return ugList;
Could there be anyone who can help a beginner?
Well, you're missing the member name you're attempting to initialize, for one. Then, you need to initialize it with a collection type, not a single UInfo instance:
...
Name = ug.Name,
UInfo = new List<UInfo>
{
new UInfo
{
...
}
}
You have ICollection<UInfo> as property, and you are using new UInfo in the code. It should be new List<UInfo>.

cant assign datatable value to list of class

This is my Model:
public class Category
{
public Category()
{
SubCategory = new List<SubCategory>();
TicketsInfo = new List<TicketInfo>();
UserDetails = new List<UserDetails>();
}
[Key]
public int CategoryId { get; set; }
public string Name { get; set; }
public List<SubCategory> SubCategory { get; set; } //subcategory is my another class
public List<TicketInfo> TicketsInfo { get; set; }//ticketinfo is my another class
public List<UserDetails> UserDetails { get; set; }//userdetails is my another class
}
This is my controller:
DataTable categoryDetailsforTickets = categoriesBal.FetchTicketDetailsforSubcategory(categoryId);
List<Category> categoryModelforTickets = new List<Category>();
if (categoryDetailsforTickets.Rows.Count != 0)
{
for (int i = 0; i < categoryDetailsforTickets.Rows.Count; i++)
{
Category categoryModel = new Category();
categoryModel.TicketsInfo[i].TicketId =(int) categoryDetailsforTickets.Rows[i].ItemArray[i];
categoryModel.UserDetails[i].FName = categoryDetailsforTickets.Rows[i].ItemArray[i].ToString();
categoryModel.TicketsInfo[i].Subject = categoryDetailsforTickets.Rows[i].ItemArray[i].ToString();
categoryModelforTickets.Add(categoryModel);
}
}
but it is throwing me error on this line:
categoryModel.TicketsInfo[i].TicketId =(int) categoryDetailsforTickets.Rows[i].ItemArray[i];
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
there are two records coming in my datatable.
can anybody figure out what is the problem???
You have to specify column also here :
categoryModel.TicketsInfo[i].TicketId =(int)categoryDetailsforTickets.Rows[i][0];
OR
categoryModel.TicketsInfo[i].TicketId =(int)categoryDetailsforTickets.Rows[i]["coloumnname"];
OR
Try iterating datatable as :-
foreach (DataRow row in categoryDetailsforTickets.Rows) // Loop over the rows.
{
categoryModel.TicketsInfo[i].TicketId =(int)row["coloumnname"];
........
}

Appending values to list of class inside viewmodel

I need to append values to a list of Class Category.
I have tried several combinations including appending 1 row at the time or append a range.
marticle.ListOfCategories.Add(crow); THiS DID NOT WORK
// marticle.ListOfCategories(ccarticle); THiS DID NOT WORK
I get the following error:
Object reference not set to an instance of an object.
Here is my category class:
public class Category
{
public int ID { get; set; }
[Required]
public string Title { get; set; }
}
And here is my view model
public class ArticleEditViewModel
{
public int ID { get; set; }
[Required]
public Boolean Active { get; set; }
[Required]
public string Title { get; set; }
public List<Category> ListOfCategories { get; set; }
}
And here is my recordset append(s) plural
public ArticleEditViewModel ArticleSelectById(int? id)
{
ArticleEditViewModel marticle = new ArticleEditViewModel();
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "content.Article_Select_ById";
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["ID"] != DBNull.Value)
{
marticle.ID = Convert.ToInt32(rdr["ID"]);
}
if (rdr["Title"] != DBNull.Value)
{
marticle.Title = rdr["Title"].ToString();
}
}
}
}
conn.Close();
//Append the list of categories
List<Category> ccarticle = new List<Category>();
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.Category_SelectAllActive";
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Category crow = new Category();
if (rdr["ID"] != DBNull.Value)
{
crow.ID= Convert.ToInt32(rdr["ID"]);
}
if (rdr["Description"] != DBNull.Value)
{
crow.Description = rdr["Description"].ToString();
}
crow.Active = true;
ccarticle.Add(crow);
marticle.ListOfCategories.Add(crow); //THiS DID NOT WORK
}
}
}
// marticle.ListOfCategories(ccarticle); THiS DID NOT WORK
}
return marticle;
}
you don't show what crow as defined as. Here is a short hand way of adding it
marticle.ListOfCategories.Add(new Category() { ID = YourID, Title = YourTitle });
just replace yourid and yourtitle with your database values. Since it is a list of Class you need to define an object of that type and add that to the list.
Edit:
before setting a list you need to initialize it
marticle.ListOfCategories = new List<Category>();
I would recommend setting this in a constructor in your class
public ArticleEditViewModel(){
ListOfCategories = new List<Category>();
}
this way everytime you create a new instance of your viewmodel the list will be automatically initialized
Edit2:
the constructor goes in the class like this
public class ArticleEditViewModel
{
public ArticleEditViewModel(){
ListOfCategories = new List<Category>();
}
public int ID { get; set; }
[Required]
public Boolean Active { get; set; }
[Required]
public string Title { get; set; }
public List<Category> ListOfCategories { get; set; }
}

The ViewData item that has the key 'distic_id' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'

In my MVC project when run and I press edit option in in view at that time this error occur
The ViewData item that has the key 'distic_id' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
In my view code
#Html.DropDownListFor(m => m.distic_id, Model.disticlist)
model is
public class city
{
public List<SelectListItem> disticlist { get; set; }
public int city_id { get; set; }
[Required]
[Display(Name = "enter the District name")]
public string city_name { get; set; }
[Required]
[Display(Name = "select district ")]
public int distic_id { get; set; }
}
if you want to get city or dist list in a drop down list please see the following code
1) Remove your code
2) Create one Model like this
3) if this drop down is used in more than one page CREATE ONE CONTROLLER like CommanController
4) write one method in this controller
See Below code
First need to create Model like this
public class Industry
{
public string Id { get; set; }
public string industryName { get; set; }
public string regexindustry { get; set; }
}
public class IndustryModel
{
public SelectList industryList { get; set; }
}
In Controller
Two Step 1 is Create one method it return type is List
and Call this method in any ActionReslut with the use of object
ViewBag.list=obj.getIndustryList();
public List<Industry> getIndustryList()
{
List<Industry> objindustry = new List<Industry>();
var connString = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlCommand sqlComm = new SqlCommand("sp_selIndustryMaster", connString);
connString.Open();
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataReader sqldr = sqlComm.ExecuteReader();
int count = 0;
while (sqldr.Read())
{
if (count == 0)
{
objindustry.Add(new Industry { Id ="", industryName = "Select Industry" });
count++;
}
else
{
objindustry.Add(new Industry { Id = Convert.ToString(sqldr["industryCode"]), industryName = sqldr["subindustry"].ToString() });
}
}
return objindustry;
}
IN VIEW
#Html.DropDownListFor(model => model.txtindustry, new SelectList(ViewBag.List, "Id", "industryName", 0))
please use it your problem may be solve,