In my UWP application: I have a SQLite data base with some points and it's coordinates. I am using Entity Framework 7 and I want to bind the data to a map control. Since I only want to keep the coordinates in the database. I created a partial class to add the other required properties to bind to the map:
//Database Fields
public partial class oFeature
{
[Key]
public string idRecord { get; set; }
public string idTag { get; set; }
public Double Latitude { get; set; }
public Double Longitude { get; set; }
public string ImageSourceUri { get; set; }
public string MoreInfo { get; set; }
}
//Binding Required Fields
public partial class oFeature
{
[NotMapped]
public Geopoint Location { get; set; }
[NotMapped]
public Point NormalizedAnchorPoint { get; set; }
[NotMapped]
public Uri UriSourceImage { get; set; }
}
To create the list for the binding I have the following code:
IQueryable<oFeature> myFeatures;
using (var db = new fldContext())
{
myFeatures = from b in db.oFeatures
select new oFeature()
{
idRecord = b.idRecord,
idTag = b.idTag,
Latitude = b.Latitude,
Longitude = b.Longitude,
ImageSourceUri = b.ImageSourceUri,
MoreInfo = b.MoreInfo,
Location = new Geopoint(new BasicGeoposition(){Latitude=b.Latitude,Longitude=b.Longitude}),
NormalizedAnchorPoint = new Point(0.5, 0.5),
UriSourceImage = new Uri("ms-appx:///Assets/green.png")
};
int recount = myFeatures.Count();
var sourceData = myFeatures.ToList();
MapItems.ItemsSource = sourceData;
}
If I remove the location line:
Location = new Geopoint(new BasicGeoposition(){Latitude=b.Latitude,Longitude=b.Longitude})
The code works but of course when I bind to the map I get an error because I have no locations. But If I keep the locations line I get an error at the line:
int recount = myFeatures.Count();
I am getting the following error:
An exception of type 'System.ArgumentNullException' occurred in System.Linq.Expressions.dll but was not handled in user code
Additional information: Value cannot be null.
{"Value cannot be null.\r\nParameter name: constructor"}
Any help would be appreciated.
Related
I have a problem with generic types in X++. I need to deserialize a JSON list yet everything I tried failed. Like using IEnumerables and JsonSerializer(does it find only AX classes and can't see references library classes?).
My helper class is in a C# library and I only need to get access to values inside the response JSON that are in list. How can I archive this in X++?
//X++
defaultException defaultException= new defaultException();
defaultException= JsonConvert::DeserializeObject(response, defaultException.GetType()); <- this gives is correct yet I cant use the values in the list
//values = FormJsonSerializer::deserializeCollection(classnum(List), response, Types::Class, 'defaultException');
// C#
public class defaultException
{
public MyException exception { get; set; }
}
public class MyException
{
public string serviceCtx { get; set; }
public string serviceCode { get; set; }
public string serviceName { get; set; }
public string timestamp { get; set;}
public string referenceNumber { get; set; }
public List<exceptionDetailList> exceptionDetailList { get; set; }
}
public class exceptionDetailList
{
public int exceptionCode { get; set; }
public string exceptionDescription { get; set; }
}
Found a solution. If we have another list in this list we need to recreate the enumerator in loop again and again as needed.
defaultException defaultException = new defaultException();
defaultException = JsonConvert::DeserializeObject(batch, defaultException.GetType());
System.Collections.IEnumerable exceptionList = defaultException.exception.exceptionDetailList;
System.Collections.IEnumerator enumerator = exceptionList.GetEnumerator();
while (enumerator.MoveNext())
{
exceptionDetailList exceptionDetailList = new exceptionDetailList();
exceptionDetailList = enumerator.Current;
}
I am trying to display data in my view using a ViewModel however I am getting null exceptions when doing so and I am not sure what the issue is. Basically I have a user, who's data I wish to display in a profile layout in my view, as well as data from different tables all in the same profile view.
ViewModel Code:
public int DonatorID { get; set; }
public string DonatorName { get; set; }
public string DonatorSurname { get; set; }
public string DonatorEmail { get; set; }
public int ContactNo { get; set; }
public int UserID { get; set; }
public string DonatorRank { get; set; }
public string RankIcon { get; set; }
public int XpAmount { get; set; }
public int TokenBalance { get; set; }
public int PaymentID { get; set; }
public string CardNo { get; set; }
public int ExpirationMonth { get; set; }
public int ExpirationYear { get; set; }
public int CVV { get; set; }
public int Zip { get; set; }
public string CardType { get; set; }
public int PaymentDonatorID { get; set; }
public int NpoID { get; set; }
public string NpoName { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
Controller Code:
id = 1;
//Disable lazy loading
db.Configuration.ProxyCreationEnabled = false;
//Add data to the dynamic object
var DynamicProfileDetail = db.tblDonator.Where(zz => zz.user_id == id).Include(yy => yy.tblUser).Include(xx => xx.tblDonator_Rank).FirstOrDefault();
DonatorUserViewModel ProfileDetails = new DonatorUserViewModel();
//Set profile details values
ProfileDetails.DonatorName = DynamicProfileDetail.donator_name;
ProfileDetails.DonatorSurname = DynamicProfileDetail.donator_surname;
ProfileDetails.DonatorEmail = DynamicProfileDetail.tblUser.email;
ProfileDetails.ContactNo = Convert.ToInt32(DynamicProfileDetail.donator_contact_no);
//Set other information
ProfileDetails.XpAmount = DynamicProfileDetail.xp_amount;
ProfileDetails.DonatorRank = DynamicProfileDetail.tblDonator_Rank.description;
ProfileDetails.RankIcon = DynamicProfileDetail.tblDonator_Rank.rank_icon;
ProfileDetails.TokenBalance = DynamicProfileDetail.donator_token_balance;
//Payment details section
int DonatorID = DynamicProfileDetail.donator_id;
var DynamicPaymentDetails = db.tblDonator_Payment_Details.Where(gg => gg.donator_id == DonatorID).Include(ff => ff.tblCard_Type).FirstOrDefault();
DonatorUserViewModel PaymentDetails = new DonatorUserViewModel();
//Set payment detail values
PaymentDetails.CardNo = DynamicPaymentDetails.donator_card_no;
PaymentDetails.ExpirationMonth = DynamicPaymentDetails.expiration_month;
PaymentDetails.ExpirationYear = DynamicPaymentDetails.expiration_year;
PaymentDetails.CVV = DynamicPaymentDetails.cvv;
PaymentDetails.Zip = DynamicPaymentDetails.zip_code;
PaymentDetails.CardType = DynamicPaymentDetails.tblCard_Type.description;
//Map marker section
var DynamicMapMarkers = db.tblNpo;
DonatorUserViewModel MapMarkers = new DonatorUserViewModel();
//Set map marker values
foreach (var item in DynamicMapMarkers)
{
MapMarkers.NpoID = item.npo_id;
MapMarkers.NpoName = item.npo_name;
MapMarkers.Longitude = Convert.ToDouble(item.longitude);
MapMarkers.Latitude = Convert.ToDouble(item.latitude);
MapMarkerList.Add(MapMarkers);
}
//ViewBags to display the relevant info
ViewBag.MapMarkerList = MapMarkerList;
return View();
My logic in the code above is that I am setting the values from my database to the objects in the ViewModel and then would be able to display it in my view.
View Code:
#model MyProject.ViewModels.DonatorUserViewModel
<h2>View/Edit your Details:</h2>
<ul>
<li>First Name: #Model.DonatorName</li>
<li>Surname: #Model.DonatorSurname</li>
<li>Contact Number: #Model.ContactNo</li>
<li>Email Address: #Model.DonatorEmail</li>
</ul>
Sorry for the amount of code in the question (particulary the viewmodel and controller sections) I just need to show that there are a lot of different objects from different database tables.
Now back to my issue, I am getting a null exception in my view for <li>First Name: #Model.DonatorName</li> and I'm assuming for the rest of them as well. I have a feeling there is something wrong with the way I am trying to use my viewmodel, as I am used to doing it using lists and then looping through that list in the view, however I am not sure how to do it now that I am only displaying essentially one line from the database tables instead of all the lines. Anyway any help would be much appreciated.
I'm trying to use the feature documented here :
https://github.com/ServiceStack/ServiceStack.OrmLite#custom-sql-customizations
This is how I'm using it:
var q = Db.From<MemberAccess>().LeftJoin<Member>();
return Db.Select<MemberResponse>(q);
Response object:
public class MemberResponse
{
public Guid Id { get; set; }
public string MemberFirstName { get; set; }
public string MemberLastName { get; set; }
public string MemberEmail { get; set; }
[Default(OrmLiteVariables.SystemUtc)]
public string AccessedOn { get; set; }
[CustomSelect("CONCAT(LEFT(Member.FirstName, 1),LEFT(Member.LastName,1))")]
public string MemberInitial { get; set; }
}
It seems like whatever I put in CustomSelect doesn't get used. Maybe, I'm not using this correctly? Also, the Default attribute doesn't work either.I tried that as it was an example from the doco.
Any idea will be appreciated.
Thanks in advance.
The [CustomSelect] only applies to the source table. Selecting the results in a custom type is used to map the returned resultset on the MemberResponse type, it doesn't have any effect on the query that gets executed.
Likewise with [Default(OrmLiteVariables.SystemUtc)] that's used to define the default value when creating the table which is only used when it creates the Column definition, so it's only useful on the source Table Type.
Both these attributes should only be added on the source MemberAccess to have any effect, which your mapped MemberResponse can access without any attributes, e.g:
public class MemberResponse
{
public Guid Id { get; set; }
public string MemberFirstName { get; set; }
public string MemberLastName { get; set; }
public string MemberEmail { get; set; }
public string AccessedOn { get; set; }
public string MemberInitial { get; set; }
}
Sql.Custom() API
The new Sql.Custom() API added in v4.5.5 that's available on MyGet will let you select a custom SQL Fragment, e.g:
var q = Db.From<MemberAccess>().LeftJoin<Member>()
.Select<MemberAccess,Member>((a,m) => new {
Id = a.Id,
MemberFirstName = m.FirstName,
MemberLastName = m.LastName,
MemberEmail = m.Email,
MemberInitial = Sql.Custom("CONCAT(LEFT(Member.FirstName,1),LEFT(Member.LastName,1))")
});
return Db.Select<MemberResponse>(q);
According to given project id(this id is coming to action as a parameter), I want to find this project and this project's issues and then I want to find some issues which has the "bug" type using linq queries in my MVC asp.net web application. But when I try below code in my action in ProjectController, I take this error: Cannot implicitly convert type 'System.Collection.Generic.List<System.Collections.Generic.List<MVCTest1.Models.Issue>>'to 'System.Collections.Generic.List<MVCTest1.Models.Issue>' and
List<Issue> issueList = (from i in db.Projects where i.projectID == projectId select i.Issues).ToList();
List<Issue> bugList = (from bug in issueList where bug. ) --> I cannot reach properties of bug issue
Here my project Model:
public class Project
{
public int projectID { get; set; }
public string projectName { get; set; }
public string descriptionProject { get; set; }
public Project parentProject { get; set; }
public string identifier { get; set; }
public DateTime date { get; set; }
public List<Project> subProjects { get; set; }
public virtual List<Issue> Issues { get; set; }
}
and my Issue Model:
public class Issue
{
public int issueID { get; set; }
public string description { get; set; }
public string subject { get; set; }
public IssueStatus? status { get; set; }
public Issue parentTask { get; set; }
public DateTime startDate { get; set; }
public DateTime dueDate { get; set; }
public int done { get; set; }
public IssuePriority? priority { get; set; }
public IssueType? type { get; set; }
public virtual List<User> Users { get; set; }
}
finally my enum:
public enum IssueType
{
Bug = 0,
Feature = 1,
Support = 2,
Operation = 3
}
Thanks in advance.
// edit 2
var project = db.Projects.Single(p => p.projectID == projectId);
var issues = project.Issues;
var bugIssues = from bug in issues where bug.type == 0 select bug;
return PartialView(bugIssues);
When I write this I got this error :
The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereListIterator1[MVCTest1.Models.Issue]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[MVCTest1.Models.Issue]'.
The problem is that your Issues property is already a List<Issue>. I suspect you want something like:
// TODO: Fix property naming...
var project = db.Projects.Single(p => p.projectId == projectId);
var issues = project.Issues;
Now issues will be a List<Issue> rather than a List<List<Issue>>.
EDIT: For the next problem, you've got an IEnumerable<Issue> but you're expecting a List<Issue>, so you need to call ToList() at that point. For example:
var project = db.Projects.Single(p => p.projectId == projectId);
return PartialView(project.Issues.Where(b => b.type == 0).ToList());
The problem is in the expected model of the MVC view, it expects a System.Collections.Generic.List<T>, but you gave a System.Linq.Enumerable.
Try do this.
return PartialView(bugIssues.ToList());
I've been searching this without any luck on how to resolve. I have a list of available departments that can be used within my stores. Since stores vary, some departments may not exist and I want to keep track of how much shelving space each department has for each store. What's the best way to create this?
Here's my model:
public class Store
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; } //StoreNumber
public virtual List<StoreDepartment> StoreDepartments { get; set; }
}
public class StoreDepartment
{
[Key]
public int ID { get; set; }
public int StoreID { get; set; }
public Department Department { get; set; }
public int ShelvingLinealFT { get; set; }
}
public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; } //DepartmentNumber
public string Name { get; set; }
public bool InActive { get; set; }
}
I've already populated my Department tables, but when I attempt to save a StoreDepartment object, I get an error stating that it can't insert a row since its trying to create a duplicate key. It's like it's trying to create a new record.
Any help would be appreciated.
Here's the code for my DbContext:
public class StoresRepository:DbContext
{
public DbSet<Store> Stores { get; set; }
public DbSet<StoreDepartment> StoreDepartments { get; set; }
public DbSet<Department> Departments { get; set; }
}
Here is my Save method:
/// <summary>
/// Saves a StoreDepartment Object to the store("dept.storeid")
/// Adds a new record if ID is 0
/// </summary>
/// <param name="dept"></param>
/// <returns></returns>
public bool Save(StoreDepartment dept)
{
bool retval = false;
try
{
using (var db = new StoresRepository())
{
if (dept.ID.Equals(0))
{
//Add Store Department
db.StoreDepartments.Add(dept);
}
else
{
//this is an update
StoreDepartment department = db.StoreDepartments.Where(p => p.ID.Equals(dept.ID)).FirstOrDefault();
department.Department = dept.Department;
department.ShelvingLinealFT = dept.ShelvingLinealFT;
}
int rowsupdated = db.SaveChanges();
retval = true;
}
}
catch (Exception ex)
{
Utils.Trace(string.Format("StoresContext.cs: StoreDepartments.Save(). ID:{1}. Exception: {0}", ex, dept.ID), Utils.ErrorTypes.Error);
}
return retval;
}
You probably change the state of the Department to added when you add the StoreDepartment object. Something like this:
using(var db = new MyContext())
{
var storeDepartment = new StoreDepartment();
storeDepartment.StoreId = storeId;
storeDeparemtent.Department = department;
db.StoreDepartments.Add(storeDepartment); // also marks Department as added
db.SaveChanges();
}
The solution is to move up the line where you add the object:
using(var db = new MyContext())
{
var storeDepartment = new StoreDepartment();
db.StoreDepartments.Add(storeDepartment);
storeDepartment.StoreId = storeId;
....
}
You can also add a DepartmentId to the StoreDepartment class and set its value, as you do with StoreId. Together with the Department property this is called a foreign key association.
I figured it out.
Here are the correct models:
public class StoreDepartment
{
[Key]
public int ID { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public int ShelvingFootage { get; set; }
}
public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public virtual ICollection<StoreDepartment> StoreDepartments { get; set; }
}
Using Affluent API, I setup my relationships as follows:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StoreDepartment>().HasRequired(d => d.Department);
modelBuilder.Entity<Department>().HasMany(d => d.StoreDepartments);
}
Once I had this setup, one of the main issues I had was with populating the object.
Normally, you would do the following:
StoreDepartment sd = new StoreDepartment();
sd.Department = new Department(){
ID = 302,
Name = "Deli"
};
sd.ShelvingFootage = 100;
However when trying to save this object, Entity would attempt to add a new record in the Department table which of course would throw an exception due to a violation in the primary key.
The trick was to not update this directly and to build my StoreDepartment object as follows:
StoreDepartment sd = new StoreDepartment();
sd.DepartmentID = 302;
sd.ShelvingFootage = 100;
By doing this, you are only updating the foreign key for the StoreDepartment.Department object.