Entity framework with linq in asp.net mvc 5 - entity-framework

I am using linq query to group by element through one table field, guid.
The problem is that I do not know how to retrieve the object on the view.
Here is my code:
public ActionResult Index2()
{
List<Imageupload> lists = db.Imageuploads.ToList();
var a = lists.GroupBy(g => g.guid);
return View(a);
}
Imageupload is a modal class and Imageuploads is a table in the database.
How can I accomplish that?

Try this:
var groupedList = db.Imageuploads
.GroupBy(u => u.guid)
.Select(g=> g.ToList())
.ToList();
Hope this helps

Related

Can Entity Framework sort entities by properties on a related entity?

Suppose I have the following "Foo" and "Bar" entities:
class Foo {
int FooId;
string FooName;
}
class Bar {
int BarId;
Foo RelatedFoo;
string BarName;
}
Let's also suppose that I want "RelatedFoo" to be lazy-loaded by default.
In Entity Framework, is it possible to do a query that returns an enumerable of "Bar" entities where elements are sorted by "bar.RelatedFoo.FooName"?
If so, can this be done in a fixed number of database queries? I would like to avoid doing N+1 queries.
If not, is this possible in another .NET ORM framework?
var bars = _context.Bars.OrderBy(b => b.RealtedFoo.FooName)
You may also want to only bring back those bars that RealtedFoo is not null
var bars = _context.Bars.Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName)
Update:
//For EF only
_context.Configuration.LazyLoadingEnabled = false
//If you want to bring back RealtedFoo then include it.
//Otherwise, you can just query for it and not use the Include() extension.
var bars = _context.Bars.Include(b => b.RealtedFoo).Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName)

Updating Foreign Key Table in EF4.1 MVC3. Object is null on POST

When i use foreign keys in the entity framework the foreign key object is null when i do a POST. I am using MVC3 and EF 4.1. I have two tables, Product and Product Details. I am exposing them using the HTML helpers in a Razor view. When the GET happens, the product details are shown. But when i do a form Submit and post to the server, the Product Details collection is null. I lose all my changes.
Any ideas what i am doing wrong?
Thanks for your help!
The Code (i shortened it because it is fairly lengthy):
Database:
Table Product
{
int Id
varchar Name
}
Table ProductDetails
{
int id,
int ProductId, <- foreign key SQL 2008 to Product Table
varchar Details
}
View:
#model WebSite.Models.Product
#{
ViewBag.Title = "MyLifeSaverStoreInfo";
}
#Html.TextBoxFor(m => m.Product.Name)
#Html.TextBoxFor(m => m.Product.ProductDetails.FirstOrDefault().Description)
Controller:
public ActionResult EditProduct(int productId)
{
var Product = _productRepository.GetProduct(productId);
return View(product);
}
[HttpPost]
public ActionResult EditProduct(Product model)
{
string name = model.Name; <- this update comes through
string description = model.ProductDetails.FirstorDefault().Description;
}
Thanks
Got it!
Instead of creating the "Product" entity on the POST EditProduct method, i use a Form Collection and then set each product detail according to that form collection and then save. I don't understand why it doesn't work the first way. I am manually updating the foreign reference. Maybe i am missing something?
[HttpPost]
public ActionResult EditProduct(int id, FormCollection formCollection)
{
var model = new MyLSstoreInfoViewModel{
StoreCurrent = _profileRepository.GetProduct(Id)
};
var productDetails = model.Product.ProductDetails.Where(p => p.productId == id).Single();
productDetaisl.Details = formCollection["details"];
if (TryUpdateModel(model.StoreCurrent))
{
_profileRepository.Save();
}
}
It's a bit late, but maybe useful for someone in the future:
If you pass the primary key of the referenced child as a hidden input in the view, it will correctly resolve the child model in the action.

Join 2 different entities from 2 different models into a single Linq to Entities query

I have a default Entity Framework model that holds all of my default tables for my product, and that all customers share in common. However, on some customers, I have some custom tables that exist for only that customer, but they relate to the default product's tables. I have a second Entity Framework model to hold these custom tables.
My question is how can I make a Linq to Entities query using Join so I can relate the entities from my default model to the tables on my custom model? I don't mind not having the Navigation properties from the custom entity to the entities on the default model; I just need a way to query both models in a single query.
Below is the code:
using (ProductEntities oProductDB = new ProductEntities())
{
using (ProductEntitiesCustom oProductCustomDB = new ProductEntitiesCustom())
{
var oConsulta = oProductCustomDB.CTBLCustoms
.Where(CTBLCustoms => CTBLCustoms.IDWOHD >= 12)
.Join(oProductDB.TBLResources,
CTBLCustoms => new
{
CTBLCustoms.IDResource
},
TBLResources => new
{
TBLResources.IDResource
},
(CTBLCustoms, TBLResources) => new
{
IDCustom = CTBLCustoms.IDCustom,
Descricao = CTBLCustoms.Descricao,
IDWOHD = CTBLCustoms.IDWOHD,
IDResource = CTBLCustoms.IDResource,
ResourceCode = TBLResources.Code
});
gvwDados.DataSource = oConsulta;
}
}
I get a The specified LINQ expression contains references to queries that are associated with different contexts error.
EDIT
Could I merge the 2 ObjectContext into a third, and then run the Linq query?
Tks
EDIT
Below is the code that worked, using the AsEnumerable() proposed solution:
using (ProductEntities oProductDB = new ProductEntities())
{
using (ProductEntitiesCustom oProductCustomDB = new ProductEntitiesCustom())
{
var oConsulta = (oProductCustomDB.CTBLCustoms.AsEnumerable()
.Where(CTBLCustoms => CTBLCustoms.IDWOHD >= 12)
.Join(oProductDB.TBLResources,
CTBLCustoms => new
{
CTBLCustoms.IDResource
},
TBLResources => new
{
TBLResources.IDResource
},
(CTBLCustoms, TBLResources) => new
{
IDCustom = CTBLCustoms.IDCustom,
Descricao = CTBLCustoms.Descricao,
IDWOHD = CTBLCustoms.IDWOHD,
IDResource = CTBLCustoms.IDResource,
ResourceCode = TBLResources.Code
})).ToList();
gvwDados.DataSource = oConsulta;
}
}
I added the AsEnumerable() as suggested, but I had to add the ToList() at the end so I could databind it to the DataGridView.
You can't do this in L2E. You could bring this into object space with AsEnumerable(), and it would work, but possibly be inefficient.
Merging the ObjectContexts is possible, and would work, but would need to be done manually.

navigating many-to-many via include in EF4

I have a many to many relationship in EF4 with the following entities:
[Student] - [Class] - [Student_Class]
Moreover i have a [School] entity with a FK on [Student].
If i want to have all the Students of my school i do:
context.School.Include("Student")
but if i want to have the 1rst class of my Students in my school ?
context.School.Include("Student").Include("Student_Class").Where(...
i did not manage to make this thing work...
Can you help ?
Also is it more intelligent to write a full Linq select?
Thanks
John
If you want to do a conditional eager load, then you should NOT be using the Include method.
For loading your school object containing only the students that belong to the first class
You can do a Filtered Projection which returns an Anonymous Type object:
var school = context.School
.Where(s => s.SchoolID == 1) // or any other predicate
.Select(s => new
{
School = s,
Students = s.Student.Where(st => st.ClassID == 1)
}).ToList();
Another way would be to Leverage Attach Method which returns EntityObject:
var school = context.School.Where(s => s.SchoolID == 1).First()
var sourceQuery = school.Students.CreateSourceQuery()
.Where(st => st.ClassID == 1);
school.Students.Attach(sourceQuery);
For a more detailed discussion about this, you can also check:
Entity Framework: How to query data in a Navigation property table

Linq query to get results from DB in ASP.NET MVC 2

How do I query using Ling to Entities.
I want to get back the total number of rows for a specific user.
I created a table with an ID(PK), Username, and PhoneNumber.
In my controller, I am able to do this and see my entities:
public ActionResult UserInfo()
{
using (UserInfoEntities db = new UserInfoEntities())
{
}
return View();
}
How do I query to return the total number of rows and declare it to a variable (totalrows) so that I can do thge following:
ViewData["TotalRows"] = totalrows
If there is a better way I am open to suggestions...
Thanks!!
Probably something like:
int count = db.SomeTable.Where(r => r.Username.Equals("username")).Count();
Yep Matthew is right. The count method does exactly what you need! Although, I would recommend looking at ViewModels to pass your data to your view (rather than ViewData) and some kind of DAL pattern, such as the repository pattern, for querying your entities.