List in Model in DB keeps on changing its order - asp.net-mvc

my db looks like this:
public class BrContext:DbContext
{
public DbSet<Conversation> AllConversations { get; set; }
public DbSet<ChatReference> ChatReferences { get; set; }
public DbSet<Product> Products { get; set; }
}
My Conversation Model looks like this:
public class Conversation
{
[Key]
public int ConversationId { get; set; }
public string ConverserName { get; set; }
public List<ChatReference> AllReferences { get; set; }
public ChatReference CurrentChatReference { get; set; }
public bool IsDealtWith { get; set; }
}
My ChatReference Model looks like this:
public class ChatReference
{
public int ChatReferenceId { get; set; }
public string ChatReferenceTime { get; set; }
public string ChatReferenceContent { get; set; }
public bool IsR { get; set; }
}
as you see - I have a list {"AllReferences"} of 'CurrentChatReference' as a property in a model that is saved in the DB.
I have times in the course of debugging the project , that when i look at the values in the DB - i see that the order of the ChatReferences in the list 'AllReferences' in the latest conversation in the db has been switched around.
Does anyone have an idea of why this is happening?

When backend query is returning the results, those results are populated in the List. If you are not sending the query using OrderBy, the results are not guaranteed to always come in the same order, so the items in the List are not always in the same order. Either you retrieve the results using OrderBy clause or Sort the results after you populate the results into your model.
Entity Framework Ordering Includes
How to Sort a List<T> by a property in the object

Related

How to make a ViewModel for an anonymous type from a linq query

I have joined and grouped 2 databases using linq in my controller, and now I need to parse it to the view. I know, I gonna need a ViewModel to do it, but I have no clue what to put in it, to make it work.
My Linq query in the controller looks like this:
var energyUsageViewModel =
from e in applicationDbContext
join u in _context.UsagesPerMonth on e.Id equals u.EnergyUsageId into u2
group u2 by new { Year = e.Year }
into u3
select u3.ToList();
return View(energyUsageViewModel);
In short what the linq query does is taking the "year" from table "e" joining it with table "u" which contains the energy usage per month, which I am gonna use to make a table in my view, which displays the year and usage per month in one row.
And currently my ViewModel looks like this (obviously not working):
public class EnergyUsageViewModel
{
public IEnumerable<UsagePerMonth> UsagePerMonthVm { get; set; }
}
The view takes a model of:
#model IEnumerable<Jullerup.Models.EnergyUsageViewModel>
I have tried to modify the ViewModel to take u3, but haven't succeeded.
I get the following invalid operation exception:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Linq.Enumerable+SelectEnumerableIterator2[System.Linq.IGrouping2[<>f__AnonymousType101[System.String],System.Collections.Generic.IEnumerable1[Jullerup.Models.UsagePerMonth]],System.Collections.Generic.List1[System.Collections.Generic.IEnumerable1[Jullerup.Models.UsagePerMonth]]]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[Jullerup.Models.EnergyUsageViewModel]'.
How do I edit my ViewModel to handle u3?
Update:
I'm working with 3 classes.
Customer class:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
//Navigation Prop
public ICollection<EnergyUsage>? energyUsage { get; set; }
}
EnergyUsage class:
public class EnergyUsage
{
public int Id { get; set; }
public int CustomerID { get; set; }
public DateTime Date { get; set; }
public int YearlyHeatUsage { get; private set; }
public List<UsagePerMonth> UsagePerYear { get; set; }
//Navigation Prop
public Customer? Customer { get; set; }
}
UsagePerMonth class:
public class UsagePerMonth
{
public int Id { get; set; }
public MonthEnum Month { get; set; }
public int Usage { get; set; }
public int HeatUsage { get; private set; }
public string EnergyType { get; set; }
private EnergyMeasurement energyType { get; set; }
public int EnergyUsageId { get; set; }
}
In the database Customer.Id (PK) has a one to many relationship to EnergyUsage.CustomerId (FK) and EnergyUsage.Id (PK) has a one to many relationship to UsagePerMonth.EnergyUsageId (FK).
What I am trying to do, is to get an object/list something I can use in the view to display all instances of UsagePerMonth grouped by Customer.Year for a certain Customer.Id.

The INSERT statement conflicted with the FOREIGN KEY constraint: Need data to be saved into two databases at the same time

I have two Models, PurchaseOrders and PurchaseOrderMessages as shown below. I am implementing this in such a way that a user, while creating a purchase order, enters the purchase order details, PurchaseOrderName and a PurchaseOrderMessage. I am using my PurchaseOrderVM for the View. On submitting the details, in the POST method, like this:
_context.Add(purchaseOrdersObj);
_context.Add(purchaseOrdersMessagesObj);
_context.SaveChanges();
I am getting the following error: The INSERT statement conflicted with the FOREIGN KEY constraint. I understand why I am getting that error. It's becuase my FOREIGN KEY, PurchaseOrderId is not present in the database yet, as the data for PurchaseOrders has not been saved.
Is there a way in which I can save the Message to the PurchaseOrderMessages the same time I save details for PurchaseOrders? Also, it has to be done in such a way that the user should be able to add more PurchaseOrderMessages in the future to the same PurchaseOrder, once the PurchaseOrder has been created. And, all the PurchaseOrderMessages should be saved so that they can all be printed on the screen one after another.
PurchaseOrders.cs
public class PuchaseOrders
{
[Key]
public int PurchaseOrderId { get; set; }
public string PurchaseOrderName { get; set; }
}
PurchaseOrderMessages.cs
public class PurhcaseOrderMessages
{
[Key]
public int UpdateId { get; set; }
public string Message { get; set; }
[ForeignKey("PurchaseOrder")]
public int PurchaseOrderId { get; set; }
public virtual PurchaseOrder PurchaseOrder { get; set; }
}
PurchaseOrderVM.cs
public class PurchaseOrderVM
{
public int PurchaseOrderId { get; set; }
public string PurchaseOrderName { get; set; }
public string Message { get; set; }
}
You need to allow EF to wire this up, so it can handle saving the objects in the right order. Instead of setting an id, set the navigation property:
purchaseOrdersMessagesObj.PurchaseOrder = purchaseOrdersObj;
_context.Add(purchaseOrdersMessageObj);
_context.SaveChanges();
You can do this by two solutions:
First:
public class PuchaseOrders
{
public PuchaseOrders(){
Messages = new List();
}
[Key]
public int PurchaseOrderId { get; set; }
public string PurchaseOrderName { get; set; }
public ICollection<PurhcaseOrderMessages> Messages{ get; set; }
}
PuchaseOrders purchaseOrdersObj= new PuchaseOrders(){ PurchaseOrderName = "Pla Pla"};
purchaseOrdersObj.Messages.Add(new PurhcaseOrderMessages(){Message = "Pla Pla"});
_context.Add(purchaseOrdersObj);
_context.SaveChanges();
Second: if you work with SP (stored procedures) in this project a lot you can write SP to take the two objects data and insert them

Viewmodel set up Aspt.net MVC 6

I'm having trouble understanding how to implement a ViewModel in Asp.net MVC, I have the following tables:
Form
ID, Data
Report
ID, FormID, Owner, Category, Status, SubmissionDate
ReportValues
ID, ReportID, Title, Value
I'm looking for a way to display and edit Report and ReportValues in the one ViewModel where ReportValues.ReportID = Report.ID
ReportValues will have multiple entries that relate to a Report.
I have had a look at similiar questions on here and tried following a tutorial ( http://techfunda.com/howto/262/list-data-using-viewmodel ) and coming up empty handed.
If you need any more information let me know and thanks in advance for any replies!
Your View Model is nothing more than a class. You can solve this many ways, but here's an example.
Create your 3 classes like you normally would.
public class Form
{
public int Id { get; set; }
public string Data { get; set; }
}
public class ReportValues
{
public int Id { get; set; }
public int ReportId { get; set; }
public string Title { get; set; }
public string Value { get; set; }
}
public class Report
{
public int Id { get; set; }
public int FormId { get; set; }
public string Owner { get; set; }
public string Category { get; set; }
public string Status { get; set; }
public DateTime SubmissionDate { get; set; }
}
Then, create your ViewModel class to include the three above classes like this.
public class ReportViewModel
{
public Form Form { get; set; }
public ReportValues ReportValues { get; set; }
public Report Report { get; set; }
}
In your view you can access your three classes and their properties as you would in your controller. Model.Form.Id
Depending on your data types, ReportValues will likely be a property of Report, but that's entirely up to your data structure. You will need to populate the classes using whatever method you want (Entity Framework, ADO, etc.) before you can pass them to your view and use them.

Entity framework migration of Collections

I have a model that looks like this
public abstract class Item
{
public int ItemId { get; set; }
public String Title { get; set; }
public String Description { get; set; }
public DateTime PurchaseDate { get; set; }
public ICollection<String> Pictures { get; set; }
public Int32 MinimumPrice { get; set; }
public DateTime Deadline { get; set; }
public Boolean VisibleBids { get; set; }
public Boolean Handled { get; set; }
public DateTime PlacementDate { get; set; }
public ApplicationUser User { get; set; }
}
In my controller I do
db.Items.ToList()
This leaves the Pictures field for all fetched objects null because its how the entity framework works. What is a good solution to fetch them in one query?
I hope you already done with Navigation properties between your tables, Now you just need to make your collection virtual and use the concept of eager loading when you need data from both the tables
public virtual ICollection<String> Pictures { get; set; }
and use include in linq like
db.Items.Include("Pictures").ToList()
So here by making virtual navigation you are saying that only take the data of related entity when you needed and whenever you need the data use the Include for eager loading.
For setting navigation properties please have a look on the code.
Suppose the scenario where we have a Post and on this we have multiple comments like
class Posts
{
public int PostsId { get; set; }
public string PostsDescription { get; set; }
public virtual ICollection<Comments> Comments { get; set; }
}
class Comments
{
public int CommentsId { get; set; }
public string CommentsDescription { get; set; }
public int PostsId { get; set; }
public virtual Posts Posts { get; set; }
}

CypherTypeException: Properties containing arrays of non-primitive types are not supported

I am getting this exception while creating nodes in NEO4J 2.0.3 using C# Client for NEO4J.
My Node Structure is like this
namespace UserGraph.BusinessObjects
{
public class UserInfo
{
public int UserID { get; set; }
public string UserName { get; set; }
public int HeadendId { get; set; }
public int Score { get; set; }
public string ThirdPartyObjID { get; set; }
public long ThirdPartyTypeId { get; set; }
public string[] ThirdPartyFriendsIds { get; set; }
public List<Programme> Programs { get; set; }
public List<Channel> Channels { get; set; }
}
public class Channel
{
public long ChannelID { get; set; }
public String ChannelName { get; set; }
}
public class Programme
{
public long ProgrammeID { get; set; }
public String ProgrammeName { get; set; }
}
}
I think Neo4j nodes don't hold Complex data. I searched and found on this link http://docs.neo4j.org/chunked/stable/graphdb-neo4j-properties.html
Can any one tell me is there any way by which i can store the list of channel and program objects in my UserInfo class.
I am running into the same issue and I am not sure I agree with the concept that all complex "properties" should be relationships. At the end of the day, the entire "node" should be something that can be serialized and stored -- this is one of the advantages of using JSON to serialize/deserialize the node. Coder the following
public class Address {
public string Line1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class User {
public string Name { get; set; }
public string email { get; set; }
public Address HomeAddress { get; set; }
public Address WorkAddress { get; set; }
}
While create nodes for Addresses can be done, I would ask the question -- why should the developer be forced to create nodes and relationships for something like this. If I never intend to do any direct queries on the properties of the Address class independently of the main user, then it is far simpler to treat the entire user as a complex object and store it in its entirety as the data for the node in the graph.

Resources