I'm not sure what is occurring here. The model was auto generated from the database and I can't see anything obvious (mind you it is 2.30am UK time at the moment so maybe I'm half asleep). I am getting the error: ActiveCitizenSystemMimic.Models.ActiveCitizenProperties does not contain a constructor that takes 2 arguments.
Model:
namespace ActiveCitizenSystemMimic.Models
{
using System;
using System.Collections.Generic;
public partial class ActiveCitizenProperties
{
public int FK_ActiveCitizen { get; set; }
public int FK_PropertyType { get; set; }
}
}
Controller:
List<ActiveCitizenProperties> activeCitizenProperties = new List<ActiveCitizenProperties>();
activeCitizenProperties.Add(new ActiveCitizenProperties(1, 2));
You may replace your code to:
List<ActiveCitizenProperties> activeCitizenProperties = new List<ActiveCitizenProperties>();
activeCitizenProperties.Add(new ActiveCitizenProperties(){ FK_ActiveCitizen = 1, FK_PropertyType = 2 });
Your "auto-generated" class obviously doesn't contain a constructor that takes 2 arguments. If it has, it would be like this:
namespace ActiveCitizenSystemMimic.Models
{
using System;
using System.Collections.Generic;
public partial class ActiveCitizenProperties
{
public int FK_ActiveCitizen { get; set; }
public int FK_PropertyType { get; set; }
public ActiveCitizenProperties(int a, int b)
{
this.FK_ActiveCitizen = a;
this.FK_PropertyType = b;
}
}
}
The errors means what it does say: ActiveCitizenProperties constructor doesn't accept two parameters. In the code given no constructor defined in the class at all.
You may use though:
new ActiveCitizenProperties { FK_ActiveCitizen = 1, FK_PropertyType = 2 };
Related
Would you help me understand why before exiting the Main function the repository.Courses is null, even though I had just added a course to the repository by calling repository.AddCourse(course); before exiting? How would I correct this? I think it may have to do with how the Courses property is defined (getter and setter). In teh getter I want to initialize by an empty list only if it's already null, otherwise I want to return the existing list. In the setter I want to assign a value - this should be correlated with the possibility of adding to list.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Repo
{
public IList<Course> _courses;
public IList<Course> Courses
{
get
{
if (_courses == null)
_courses = new List<Course>();
return new List<Course>(_courses);
}
set
{
_courses = value;
}
}
public void AddCourse(Course course)
{
course.Id = Courses.NextId();
Courses.Add(course);
}
static void Main(string[] args)
{
Repo repository = new Repo();
var path = "C:\\a1\\demos\\demo1-after\\ConsoleApplication1\\json1.json";
var reader = new StreamReader(path);
string text = reader.ReadToEnd();
var course = JsonConvert.DeserializeObject<Course>(text);
repository.AddCourse(course);
}
}
public class Course : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public Course(string n, string a)
{
Name = n;
Author = a;
}
}
public interface IEntity
{
int Id { get; set; }
}
public static class Extensions
{
public static int NextId<T>(this IList<T> list) where T : IEntity
{
return list.Any() ? list.Max(x => x.Id) + 1 : 0;
}
}
}
The problem here is that your get is always returning a new list, rather than the backing field.
Try this instead:
get
{
if (_courses == null) _courses = new List<Course>();
return _courses;
}
I noticed that the getter of Courses returns a new list rather than a reference to the field. Is that because you don't want anyone from outside the class to be able to add anything to the list except through AddCourse?
In this case the fix I'd recommend is to change AddCourse to address the field directly rather than the property, as currently it's adding the item to the new list created by the getter rather than to the list referenced by your field.
I'm an intern with very basic knowledge of ASP and C#.
I'm trying to display a list of projects > maps > thememaps in an application I'm working on in ASP.NET MVC. In my third foreach I get an error saying: "Does not contain a definition for "ThemeMaps" and no extension method "ThemeMaps" accepting a first argument of type could be found".
I'm confused as to why vmProject.Maps does not contain the property ThemeMaps. I instantiated that list just like maps. What am I doing wrong?
LayersController.cs
// Create viewmodel object
var viewModel = new AddLayerToThemeMapViewModel();
// Create Project list
viewModel.Projects = new List<AddProject>();
// Loop over all maps
List<Project> projects = this.applicationDb.Projects.OrderBy(e => e.Title).ToList();
foreach (var project in projects)
{
// Create map
var vmProject = new AddProject()
{
ProjectId = project.ProjectID,
ProjectTitle = project.Title,
Maps = new List<AddLayerMap>(),
};
foreach (var map in project.Maps.OrderBy(e => e.Title))
{
// Create map
vmProject.Maps.Add(new AddLayerMap()
{
MapId = map.MapId,
MapTitle = map.Title,
ThemeMaps = new List<AddLayerMapThemeMap>(),
});
// Loop over all thememaps in map
foreach (var thememap in map.ThemeMaps.OrderBy(e => e.Order))
{
vmProject.Maps.ThemeMaps.Add(new AddLayerMapThemeMap()
{
ThemeMapId = thememap.ThemeMapId,
ThemeMapTitle = thememap.Title,
});
}
}
// Add map to list
viewModel.Projects.Add(vmProject);
}
My viewmodel class
using Mapgear.MapViewer.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mapgear.MapViewer.ViewModels
{
public class AddLayerToThemeMapViewModel
{
public Guid LayerId { get; set; }
public List<AddProject> Projects { get; set; }
}
public class AddProject
{
public Guid ProjectId { get; set; }
public string ProjectTitle { get; set; }
public List<AddLayerMap> Maps { get; set; }
}
public class AddLayerMap
{
public Guid MapId { get; set; }
public string MapTitle { get; set; }
public List<AddLayerMapThemeMap> ThemeMaps { get; set; }
}
public class AddLayerMapThemeMap
{
public Guid ThemeMapId { get; set; }
public string ThemeMapTitle { get; set; }
}
}
I made a scetch before I started on paper, which looks like the following:
LayerId
List project
ProjectId
ProjectTitle
List Map
MapId
MapTitle
List ThemeMap
ThemeMapId
ThemeMapTitle
I know my class names are a bit out of wack, however I din't write them myself. Gonna optimize them after.
PS: This is my first question on StackOverflow!
I modified the code in the second for-each loop a bit. I added a variable for the newly created map and add the thememaps to this created map. Check if it's correct.
var newMap = new AddLayerMap()
{
MapId = map.MapId,
MapTitle = map.Title,
ThemeMaps = new List<AddLayerMapThemeMap>(),
};
// Create map
vmProject.Maps.Add(newMap);
// Loop over all thememaps in map
foreach (var thememap in map.ThemeMaps.OrderBy(e => e.Order))
{
newMap.ThemeMaps.Add(new AddLayerMapThemeMap()
{
ThemeMapId = thememap.ThemeMapId,
ThemeMapTitle = thememap.Title,
});
}
I am trying to pull the properties from the PullConstants class to the CreateForecast class. In CreateForecast, I have created an instance of PullConstants with this code. I have also verified that both classes are in the same namespace.
PullConstants pc = new PullConstants();
However, when I try to pull a value from PullConstants to CreateForecast with code below, I always receive 0.
double sla = pc.sla;
I have verified that the value gets pulled from the database correctly, but its scope seems to not reach beyond the first run of the class. What exactly am I doing wrong that I am not able to pull the correct property value from PullConstants?
The PullConstants class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ForecastBuilder
{
class PullConstants
{
InitializeDB idb = new InitializeDB();
ErrorLogger el = new ErrorLogger();
public double sla { get; set; }
public int serviceTime { get; set; }
public int avgHandleTime { get; set; }
public int maxWait { get; set; }
public double shrinkageAdjustment { get; set; }
public double alpha { get; set; }
public double beta { get; set; }
public double specialDayPerInc { get; set; }
public void PullConstantValues()
{
idb.OpenDatabases();
try
{
string sqlConstants = "select * from forecastconstants";
MySqlCommand cmdConstants = new MySqlCommand(sqlConstants, idb.myconn);
MySqlDataReader rdrConstants = cmdConstants.ExecuteReader();
while (rdrConstants.Read())
{
sla = double.Parse(rdrConstants["SLA"].ToString());
serviceTime = int.Parse(rdrConstants["ServiceTime"].ToString());
avgHandleTime = int.Parse(rdrConstants["AvgHandleTime"].ToString());
maxWait = int.Parse(rdrConstants["MaxWait"].ToString());
shrinkageAdjustment = double.Parse(rdrConstants["ShrinkageAdjustment"].ToString());
alpha = double.Parse(rdrConstants["Alpha"].ToString());
beta = double.Parse(rdrConstants["Beta"].ToString());
specialDayPerInc = double.Parse(rdrConstants["SitCallIncrPer"].ToString());
}
}
catch (Exception e)
{
el.createError(2, e.ToString(), "Could not pull constants");
}
finally
{
idb.myconn.Close();
}
}
}
}
I guess you are missing the call to PullConstantValues:
PullConstants pc = new PullConstants();
pc.PullConstantValues();
double sla = pc.sla;
If supplying these values is the only purpose of this class you may are better of using it as a constructor:
class PullConstants
{
/* ... */
public PullConstants() // instead of 'void PullConstantValues()'
{
/* ... */
}
}
If the are "real constants" may also use a singleton to not query the DB every time.
Either you are misssing a call to this function
public void PullConstantValues();
or you may consider making this function a constructor by changing it to
public PullConstant();
I have 3 class. Those are places.cs, onePlace.cs and placestovisit.cs.
placestovisit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class placestovisit
{
public bool IsDataLoaded { get; set; }
public onePlace sunamganj { get; set; }
public static string basePlaces = "Assets/Places/";
private string baseTanguar = basePlaces + "Tanguar/";
private string baseBaruni = basePlaces + "Baruni/";
public void LoadData()
{
sunamganj = createSunamganj();
IsDataLoaded = true;
}
private onePlace createSunamganj()
{
onePlace data = new onePlace();
data.Items.Add(new places()
{
ID = "0",
Title = "Tanguar Haor",
shortDescription="Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District.",
itemImage = baseTanguar + "1.jpg",
FullDescription = "Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District. The marshes are inter connected with one another through narrow Channels but merge into a single large water body during monsoon. The aquatic vegetation and less disturbance from the human are instrument to invite a large variety of waterfowl specially winter migrant ducks that congregates in thousands. Resident and local migrant, raptor, waders and passerine birds made the area as one of the Asia's most potential birding place. Tanguar Haor is listed as a Ramsar site under the Ramsar Convention in 2000."
});
}
}
onePlace.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class onePlace
{
public string Title { get; set; }
public List<places> Items { get; set; }
public onePlace()
{
Items = new List<places>();
}
}
}
places.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class places
{
public string ID { get; set; }
public string Title { get; set; }
public string shortDescription { get; set; }
public string FullDescription { get; set; }
public string itemImage { get; set; }
public List<string>Gallery { get; set; }
}
}
I want to add item into Gallery from placestovisit class. For that what to do?
Actually I want to add one photo gallery for each object. But I am not so much good in OOP. At this moment can I go with this concept or need to change the concept. If I can go with this one then how can I add item into Gallery from placestovisit class?
Gallery is just a property of your places class, and you can add items by accessing that property via an instance of places class.
One thing you should remember that the properties of reference types are null by default, so you need to initialize them.You can do that in your constructor:
public class places
{
public places()
{
Gallery = new List<string>();
}
}
Then you can add new items to your list like:
var plc = new places() { /* set the properties */ }
plc.Gallery.Add("new gallery");
I am quite certain that questions like this have been answered a number of times before, but I can't get any of the suggestions to work.
I am building a MVC 4 application with Entity Framework 5, where the entities were generated from existing tables. I have entity classes that look like this:
namespace RebuildingModel
{
using System;
using System.Collections.Generic;
public partial class StandardCodeTable
{
public StandardCodeTable()
{
this.StandardCodeTableTexts = new HashSet<StandardCodeTableText>();
}
public int TableCode { get; set; }
public string RefTableName { get; set; }
public virtual ICollection<StandardCodeTableText> StandardCodeTableTexts { get; set; }
}
}
namespace RebuildingModel
{
using System;
using System.Collections.Generic;
public partial class StandardCodeTableText
{
public int TableCode { get; set; }
public string LanguageCode { get; set; }
public string TextVal { get; set; }
public virtual StandardCodeTable StandardCodeTable { get; set; }
}
}
namespace RebuildingSite.Models
{
public class CodeTableJoined
{
public int TableCode { get; set; }
public string ReferenceTableName { get; set; }
public string LanguageCode { get; set; }
public string TextValue { get; set; }
}
}
I have a DAO that looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RebuildingModel.Dao
{
public class CodeTableDao
{
public CodeTableDao() { }
public ISet<StandardCodeTableText> GetCode(string refTableName)
{
HashSet<StandardCodeTableText> codes = new HashSet<StandardCodeTableText>();
using (var db = new RebuildingTogetherEntities())
{
db.StandardCodeTableTexts.Include("StandardCodeTables");
var query = from c in db.StandardCodeTableTexts
where c.StandardCodeTable.RefTableName == refTableName
orderby c.TableCode
select c;
foreach (var item in query)
{
codes.Add(item);
}
}
return codes;
}
}
I have a controller that looks like this:
namespace RebuildingSite.Controllers
{
public class CodeTableController : Controller
{
public ActionResult Index(string refTableName)
{
CodeTableDao dao = new CodeTableDao();
ICollection<StandardCodeTableText> codes = dao.GetCode(refTableName);
HashSet<CodeTableJoined> joins = new HashSet<CodeTableJoined>();
foreach (var code in codes)
{
CodeTableJoined join = new CodeTableJoined();
join.TableCode = code.TableCode;
join.LanguageCode = code.LanguageCode;
join.TextValue = code.TextVal;
join.ReferenceTableName = code.StandardCodeTable.RefTableName;
joins.Add(join);
}
ISet<string> refTableNames = dao.GetReferenceTables();
ViewBag.RefTableNames = refTableNames;
return View(joins);
}
}
}
When I run the view attached to the controller, an ObjectDisposedException is thrown at this line, where the relationship is used:
join.ReferenceTableName = code.StandardCodeTable.RefTableName;
This has to be something simple. What am I doing wrong? I have tried adding that Include() call in from the context in many different places, even multiple times.
I've also tried adding an explicit join in the Linq query. I can't get EF to fetch that relationship.
Copying my comment to an answer - Put the include be in the actual query
var query = from c in
db.StandardCodeTableTexts.include("StandardCodeTables"). where
c.StandardCodeTable.RefTableName == refTableName orderby c.TableCode
select c;