Retrieve multiple list from grandchild entity using lambda - c#

I've three entities, say Parent, Child & GrandChild. This GrandChild has got three lists(a,b & c).
How to retrive all these lists using "Include" in Entity Framework?
I can retrive one list like this: Include("Parent.Child.GrandChild.a"),
but when I add another Include like : Include("Parent.Child.GrandChild.b"), it throws an error.
How will i retrive all these lists in a single query?
My code is as follows:
objUserNew = objContaxt.ContextRegistration
.Include("listing.postlist.commentslist")
.Include(‌​"listing.postlist.taglist")
.Include("listing.postlist.knocklist")
.FirstOrDefault(‌​x => x.id == objUser.id);
public class registration
{
public int id { get; set; }
public string firstname { get; set; }
public forgtPass forgtPass { get; set; }
public List<listing> listing { get; set; }
}
public class listing
{
public int id { get; set; }
public string address { get; set; }
public List<post> postlist { get; set; }
}
public class post
{
public int id { get; set; }
public string imgUrl { get; set; }
public List<tag> taglist { get; set; }
public List<comments> commentslist { get; set; }
public List<knoqs> knoqs { get; set; }
}
public class tag
{
public string name { get; set; }
}
public class comments
{
public int id { get; set; }
public string comment { get; set; }
public status status { get; set; }
}
public class knoqs
{
public int id { get; set; }
public virtual int registration_id { get; set; }
[ForeignKey("registration_id")] public registration registration { get; set; }
public status status { get; set; }
}

Related

How to filter SelectList contents

How to filter the SelectList so that I only get ClassifierElements where Classifier.Name == "CellTypes"? Is it even doable? Should I use a different kind of object like IEnumerable?
In CellController:
ViewData["TypeId"] = new SelectList(_context.ClassifierElements, "Id", "Name");
Here are the objects:
public class Cell
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public ClassifierElement Type { get; set; }
public ICollection<Component> Components { get; set; }
public ICollection<Parameter> Parameters { get; set; }
}
public class Classifier
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ClassifierElement> ClassifierElements { get; set; }
}
public class ClassifierElement
{
public int Id { get; set; }
public int ClassifierId { get; set; }
public Classifier Classifier { get; set; }
public string Name { get; set; }
}
You can use a Linq expression to filter the list:
_context.ClassifierElements.Where(e => e.Name == "CellTypes")

Noob C# Class Declaration Issue

So I created a class using json2csharp
public class ResponseType
{
public class Query
{
public string q { get; set; }
public object sku { get; set; }
public int limit { get; set; }
public object reference { get; set; }
public object mpn_or_sku { get; set; }
public string mpn { get; set; }
public object brand { get; set; }
public string __class__ { get; set; }
public int start { get; set; }
public object seller { get; set; }
}
public class Request
{
public bool exact_only { get; set; }
public string __class__ { get; set; }
public List<Query> queries { get; set; }
}
public class Seller
{
public string display_flag { get; set; }
public bool has_ecommerce { get; set; }
public string name { get; set; }
public string __class__ { get; set; }
public string homepage_url { get; set; }
public string id { get; set; }
public string uid { get; set; }
}
public class Prices
{
public List<List<object>> USD { get; set; }
public List<List<object>> JPY { get; set; }
public List<List<object>> CNY { get; set; }
}
public class Offer
{
public string sku { get; set; }
public string packaging { get; set; }
public string on_order_eta { get; set; }
public string last_updated { get; set; }
public int? order_multiple { get; set; }
public int in_stock_quantity { get; set; }
public string eligible_region { get; set; }
public int? moq { get; set; }
public int? on_order_quantity { get; set; }
public object octopart_rfq_url { get; set; }
public string __class__ { get; set; }
public Seller seller { get; set; }
public string product_url { get; set; }
public object factory_order_multiple { get; set; }
public string _naive_id { get; set; }
public int? factory_lead_days { get; set; }
public Prices prices { get; set; }
public bool is_authorized { get; set; }
public bool is_realtime { get; set; }
}
public class Brand
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Manufacturer
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Item
{
public List<Offer> offers { get; set; }
public string uid { get; set; }
public string mpn { get; set; }
public List<object> redirected_uids { get; set; }
public Brand brand { get; set; }
public string octopart_url { get; set; }
public string __class__ { get; set; }
public Manufacturer manufacturer { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
public int hits { get; set; }
public string __class__ { get; set; }
public object reference { get; set; }
public object error { get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}
}
The problem is at design-time, when I declare a variable with the type of my class:
ResponseType Response = new ResponseType();
Intellisense does not allow me to access the subclasses RootObject.results list. It only shows Equals, GetHashCode, GetType and ToString. I am assuming I did something wrong in my class declaration.
Thank you in advance!
Edit -- I am fairly new to C Sharp. I am trying to parse a response from a REST API. I took the JSON provided by the Rest API and converted it using json2csharp into a class. My intent was to do something like this
Within a function return:
public ResponseType ExecuteSearch(String PartNumber)
{
~ ALL CODE FOR GENERATING req
// Perform the search and obtain results
var data = client.Execute(req).Content;
JSON = data;
return JsonConvert.DeserializeObject<ResponseType>(data);
}
Then being able to access the response as an object outside of the function
Edit 2:
I figured out what I did. Instead of nesting everything within the ResponseType I should have simply renamed RootObject to ResponseType.
Intellisense does not allow me to access the subclasses RootObject.results list
it is because the property results is not static and you try to acces it this way. A static property is accessed via ClassName.PropertyName. For more information on static variables check the link.
It only shows Equals, GetHashCode, GetType and ToString
This is the basic set of methods that every object in C# inherits from the class object. This is why you can see it.
Intellisense will allow you to do this:
ResponseType.RootObject ro = new ResponseType.RootObject();
ro.results.First();
because you will need an Instance of that class to acces the property results.
I am assuming I did something wrong in my class declaration.
It depends. Basically if the compiler does not complain then you declared your classes as supposed to be. But the declaration of the properties commands you to access them in a specific way. So if you still want to access results with RootObject.results you need to make it static:
public class RootObject
{
public static List<Result> results { get; set; }
}
But note that this list will exist only once! and is not individual to each instance of RootObject! Since you have embedded classes you need to call it like this:
ResponseType.RootObject.results.WhatEver();
EDIT
I guess you would like to get the Object of type RootObject inside the Object of type ResponseType. If I am right then it is not necessary to declare the classes inside ResponseType but you have to declare variables of each type inside it like:
public class ResponseType
{
public RootObject MyRootObject{ get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}
Now you will be able to access the results variable inside the ResponseType object:
ResponseType rt = new ResponseType();
rt.MyRootObject.results.WhatEver();
For more information on how to deserialize JSON to classes please read the Deserialize JSON to C# Classes post
1) Object with ResponseType class isn't contain any fields(event static one).
2) You declare ResponseType object, but results is field of RootObject object.
So if you want to work with results you should do something like this:
ResponseType.RootObject rootObject = new ResponseType.RootObject();
rootObject.results.DoWork();
Below is what I think you are trying to do. I would only use it in this form if this is some kind of Data Transfer Object (DTO) because otherwise it is pretty bad practice for a class that would be used in code (mostly because of the public getters and setters on all of the fields and the field names matching the class name), but it does show your main mistake and that is that classes need to be defined outside of your main class and if you need that type of class in your top level class you need to define a public field to access it.
public class ResponseType
{
public Query Query { get; set; }
public Request Request { get; set; }
public Seller Seller { get; set; }
public Prices Prices { get; set; }
public Offer Offer { get; set; }
public Brand Brand { get; set; }
public Manufacturer Manufacturer { get; set; }
public Item Item { get; set; }
public Result Result { get; set; }
public RootObject RootObject { get; set; }
}
public class Query
{
public string q { get; set; }
public object sku { get; set; }
public int limit { get; set; }
public object reference { get; set; }
public object mpn_or_sku { get; set; }
public string mpn { get; set; }
public object brand { get; set; }
public string __class__ { get; set; }
public int start { get; set; }
public object seller { get; set; }
}
public class Request
{
public bool exact_only { get; set; }
public string __class__ { get; set; }
public List<Query> queries { get; set; }
}
public class Seller
{
public string display_flag { get; set; }
public bool has_ecommerce { get; set; }
public string name { get; set; }
public string __class__ { get; set; }
public string homepage_url { get; set; }
public string id { get; set; }
public string uid { get; set; }
}
public class Prices
{
public List<List<object>> USD { get; set; }
public List<List<object>> JPY { get; set; }
public List<List<object>> CNY { get; set; }
}
public class Offer
{
public string sku { get; set; }
public string packaging { get; set; }
public string on_order_eta { get; set; }
public string last_updated { get; set; }
public int? order_multiple { get; set; }
public int in_stock_quantity { get; set; }
public string eligible_region { get; set; }
public int? moq { get; set; }
public int? on_order_quantity { get; set; }
public object octopart_rfq_url { get; set; }
public string __class__ { get; set; }
public Seller seller { get; set; }
public string product_url { get; set; }
public object factory_order_multiple { get; set; }
public string _naive_id { get; set; }
public int? factory_lead_days { get; set; }
public Prices prices { get; set; }
public bool is_authorized { get; set; }
public bool is_realtime { get; set; }
}
public class Brand
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Manufacturer
{
public string homepage_url { get; set; }
public string __class__ { get; set; }
public string name { get; set; }
public string uid { get; set; }
}
public class Item
{
public List<Offer> offers { get; set; }
public string uid { get; set; }
public string mpn { get; set; }
public List<object> redirected_uids { get; set; }
public Brand brand { get; set; }
public string octopart_url { get; set; }
public string __class__ { get; set; }
public Manufacturer manufacturer { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
public int hits { get; set; }
public string __class__ { get; set; }
public object reference { get; set; }
public object error { get; set; }
}
public class RootObject
{
public int msec { get; set; }
public Request request { get; set; }
public string __class__ { get; set; }
public List<Result> results { get; set; }
}

How can I connect the fields of two tables in MVC 5?

I have two models and for which I will create tables through migration and database update. My first model is named Service, and it consists of these fields:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public int Count { get; set; }
}
My second model is called Business, and it has the following fields:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}
The point is that I want to add Category and Subcategory fields into my Business model, but the values of Category and Subcategory fields, should be one of the values inside the Service table's values for Category and Subcategory.
Simply, I want to connect those two fields. How can I achieve it? Should I just put a Service property inside the Business model?
Break out a separate entity for "Category" and then use foreign keys:
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Service
{
...
public virtual Category Category { get; set; }
public virtual Category Subcategory { get; set; }
}
// Do the same when adding category/subcategory fields to `Business`
If you want to ensure that these categories are only tied to Service (and you potentially have other types of categories or something) you can always just make the entity ServiceCategory or something and only create a relationship to it from Service.
You need to separate your break out your database to store lookup table for category and a lookup table for subcategory.
Then you can create:
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class SubCategory {
public int SubCategoryId { get; set; }
public string Name { get; set; }
}
Then change your service class to:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public int CategoryId { get; set; }
public int SubcategoryId { get; set; }
public int Count { get; set; }
}
and change your Business class to:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}

deserializing an object with a generic list

I am trying to deserialize an object, the type is populated but I am getting null for the List<Sport>. Any ideas?
My classes:
class Sports
{
public MsgTypes type { get; set; }
public List<Sport> Sport { get; set; }
}
class Sport
{
public int Id { get; set; }
public int Import_id { get; set; }
public string Name { get; set; }
public int Active { get; set; }
public int Order { get; set; }
public int Min_bet { get; set; }
public int Max_bet { get; set; }
public int Updated { get; set; }
public string Feed_type { get; set; }
public string Locale { get; set; }
}
The command for deserialization:
Sports _sports = (Sports) JsonConvert.DeserializeObject<Sports>(jsonObj);
This is my JSON object:
"{\"code\":0,\"type\":4,\"Sports\":[{\"Sport\":{\"id\":\"1\",\"import_id\":\"1\",\"name\":\"Soccer\",\"active\":true,\"order\":\"1\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194889\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"2\",\"import_id\":\"5\",\"name\":\"Tennis\",\"active\":true,\"order\":\"3\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194771\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"3\",\"import_id\":\"6\",\"name\":\"Handball\",\"active\":true,\"order\":\"6\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403152901\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"4\",\"import_id\":\"4\",\"name\":\"Ice Hockey\",\"active\":true,\"order\":\"4\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403080245\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"7\",\"import_id\":\"2\",\"name\":\"Basketball\",\"active\":true,\"order\":\"2\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194830\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"8\",\"import_id\":\"23\",\"name\":\"Volleyball\",\"active\":true,\"order\":\"5\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194591\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"9\",\"import_id\":\"12\",\"name\":\"Rugby\",\"active\":true,\"order\":\"7\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194710\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"12\",\"import_id\":\"11\",\"name\":\"Motorsport\",\"active\":true,\"order\":\"12\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403065699\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"13\",\"import_id\":\"3\",\"name\":\"Baseball\",\"active\":true,\"order\":\"13\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194834\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"14\",\"import_id\":\"16\",\"name\":\"American Football\",\"active\":true,\"order\":\"14\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403143326\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"16\",\"import_id\":\"34\",\"name\":\"Beach Volley\",\"active\":true,\"order\":\"16\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194417\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}}]}"
You need one more level of nesting and different class names. You should be able to deserialize to such structure:
class SportsParent
{
//Code for MsgTypes was not provided so it is commented out
public List<SportGroup> Sports { get; set; }
}
class SportGroup
{
public SportItem Sport { get; set; }
}
class SportItem
{
public int Id { get; set; }
public int Import_id { get; set; }
public string Name { get; set; }
public bool Active { get; set; } //need to be converted to bool instead of int
public int Order { get; set; }
public int Min_bet { get; set; }
public int Max_bet { get; set; }
public int Updated { get; set; }
public string Feed_type { get; set; }
public string Locale { get; set; }
}
You can deserialize using such code:
SportsParent _sports = JsonConvert.DeserializeObject<SportsParent>(jsonObj);

Error with Entity Framework 4 and MVC 3

I have a database with 3 tables:
Subjects
Members
Topics
Then I added the connection string to web.config and created an EF with the following classes:
namespace MySite.Models
{
public class MySiteDBModel : DbContext
{
public DbSet<Topic> Topics { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<TopicDataModel> TopicDataModel { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class Topic
{
[Key]
public int TopicID { get; set; }
public int SubID { get; set; }
public int MemberID { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public string FileName { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
public virtual Subject Subject { get; set; }
public virtual Member Member { get; set; }
public virtual ICollection<TopicView> TopicView { get; set; }
}
public class Subject
{
[Key]
public int SubID { get; set; }
public string SubName { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class Member
{
[Key]
public int MemberID { get; set; }
public string FLName { get; set; }
public string Email { get; set; }
public string Pwd { get; set; }
public string About { get; set; }
public string Photo { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class TopicDataModel
{
[Key]
public int TopicID { get; set; }
public string SubName { get; set; }
public string FLName { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
}
}
Now when I am trying to query the database with the this code:
public ActionResult Index()
{
var topics = from t in db.Topics
join s in db.Subjects on t.SubID equals s.SubID
join m in db.Members on t.MemberID equals m.MemberID
select new TopicDataModel()
{
TopicID = t.TopicID,
SubName = s.SubName,
FLName = m.FLName,
TDate = t.TDate,
Title = t.Title,
Displays = t.Displays,
Description = t.Description
};
return View(topics.ToList());
}
I got this Error:
The model backing the 'MySiteDBModel' context has changed since the
database was created. Either manually delete/update the database, or
call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will
automatically delete and recreate the database, and optionally seed it
with new data.
Please help me!!!!!!
You need to set some controls on how EF is handling changes to your data model. Julie Lerman has a good blog post on Turning Off Code First Database Initialization Completely.
Also, here is a good overview - Inside Code First Database Initialization

Categories