I want to get all these values from table Trouble and paste into Combobox.
I have this code,but i get System.ObjectDisposedException error
var items = db.Trouble.Where(u => u.id_Проблемы > 0).Select(u => u.id_Проблемы);
id_Trouble_box.Items.Add(items);
You should force Immediately excution by .ToArray() or ToList()
var items = db.Trouble.Where(u => u.id_Проблемы > 0).Select(u => u.id_Проблемы).ToArray();
id_Trouble_box.Items.Add(items);
Read the following thread to have a better understanding.
LINQ performance - deferred v/s immediate execution
Add a .ToArray() at the end. Perhaps you have it adding items outside a using statement.
If you want to select them all then you don't need a Where criteria:
var items = db.Trouble();
and to add to a combo you could set the DataSource:
var items = db.Trouble();
id_Trouble_box.DataSource = items.ToList();
id_Trouble_box.DisplayMember = "columnToShow"; // display column
id_Trouble_box.ValueMember = "id_Проблемы"; // id to get on selection as a value
EDIT: For those who don't understand why this answer fixes the error:
string defaultConString = #"server=.\SQLExpress;Database=Northwind;Trusted_Connection=yes;";
void Main()
{
Form f = new Form();
ComboBox cb = new ComboBox { Top = 10, Left = 10 };
f.Controls.Add(cb);
using (var ctx = new MyContext(defaultConString))
{
var items = ctx.Customers.Where(c => c.ContactName.Contains("a")).Select(c => c.CompanyName);
cb.Items.Add(items);
}
f.Show();
}
public class MyContext : DbContext
{
public MyContext(string connectionString)
: base(connectionString)
{ }
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
[Key]
public string CustomerId { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
// ...
// public virtual List<Order> Orders { get; set; }
}
I solved the problem this way
var items = db.Trouble.Where(u => u.id_Проблемы > 0).Select(u => u.id_Проблемы).ToArray();
for(int i = 0; i < items.Length; i++)
{
id_Trouble_box.Items.Add(items[i]);
}
Related
I want to show only the rows from one table that meet a certain condition in another table. Example on the controller:
using(inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
ProductandBodViewModel finalitem = new ProductandBodViewModel();
var m_List = dc.showcase.Where(x => x.prod_on_showcase > 0).ToList();
}
With the code above it's possible to display only the items that meets the condition, prod_on_showcase > 0. The ProductandBodViewModel is a model that I created to show two models on a same view.
The ProductandBodViewModel model:
public class ProductandBodViewModel
{
public List<inventory> inventory { get; set; }
public List<showcase> showcase { get; set; }
}
According to this condition (prod_on_showcase > 0) I want to show other information that is related to the table showcase table.
The model of the showcase table:
public class showcaseViewModel
{
public int id_inventory { get; set; }
public int prod_on_showcase { get; set; }
}
The model of the inventory table:
public partial class inventory
{
public int id_inventory { get; set; }
public Nullable<int> prod_on_inventory { get; set; }
public string prod_code { get; set; }
}
The relation between the tables is the id_inventory field.
In this case, the items displayed for the showcase table are 3, so the inventory table must also display 3 items.
With the code below it's possible to display info of the table showcase that meets the condition but with the other table (inventory) only display the first element that it's found according to the condition prod_on_showcase > 0.
using(inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
ProductandBodViewModel finalitem = new ProductandBodViewModel();
var m_List = dc.showcase.Where(x => x.prod_on_showcase > 0).ToList();
var m_Each = dc.showcase.Where(e => e.prod_on_showcase > 0).Count();
for(int i = 0; i < m_Each; i++)
{
var prodEach = dc.inventory.Where(x => x.prod_on_showcase > 0).FirstOrDefault();
var b = dc.inventory.Where(a => a.id_inventory == prodEach.id_inventory).ToList();
finalitem.bod = b;
}
finalitem.showcase = m_List;
return View(finalitem);
}
You're asking var prodEach = dc.inventory.Where(x => x.prod_on_showcase > 0).FirstOrDefault(); to always return the First(or default) element in the array.
Linq's SelectMany is useful for what you're trying to do.
using(inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
ProductandBodViewModel finalitem = new ProductandBodViewModel();
var m_List = dc.showcase.Where(x => x. > 0).ToList();
var m_List = showcase.Where(x => x.prod_on_showcase > 0).ToList();
finalitem.showcase = m_List.SelectMany(prodEach
=> dc.inventory.Where(a => a.id_inventory == prodEach.id_inventory)
finalitem.showcase = m_List;
return View(finalitem);
}```
Hi i want to write sql Group by query in C# of my MVC5 application.
In the above image I have group by query which i wrote in sql . That I want to write in C# front end.
I tried to write query in front end. But I am getting error which is mentioned in the image. Now I want to write that Group By query in C# and want to display the each employee with count (output same as mentioned in the first image). Can anyone help me to resolve this issue?
My ViewModel(Dashnboard View model)
public class DashboardViewmodel
{
public List<CustomerTypeCountModel> CustomerTypesCountModels { get; set; }
public List<View_VisitorsForm> Visits { get; set; }
public CustomerTypeViewModel CustomerTypeViewModels { get; set; }
public int sizingcount { get; set; }
public int Processingcount { get; set; }
//here i declared two properties
public string EmployeeName { get; set; }
public string EmployeeCount { get; set; }
}
My Controller code
[HttpGet]
public ActionResult SalesVisit()
{
return View();
}
public ActionResult GetDatesFromSalesVisit(DashboardViewmodel dvm)
{
var fromdate = Convert.ToDateTime(dvm.CustomerTypeViewModels.FromDate);
var todate = Convert.ToDateTime(dvm.CustomerTypeViewModels.ToDate);
List<View_VisitorsForm> empcount = new List<View_VisitorsForm>();
if (DepartmentID == new Guid("47D2C992-1CB6-44AA-91CA-6AA3C338447E") &&
(UserTypeID == new Guid("106D02CC-7DC2-42BF-AC6F-D683ADDC1824") ||
(UserTypeID == new Guid("B3728982-0016-4562-BF73-E9B8B99BD501"))))
{
var empcountresult = db.View_VisitorsForm.GroupBy(G => G.Employee)
.Select(e => new
{
employee = e.Key,
count = e.Count()
}).ToList();
empcount = empcountresult ;//this line i am getting error
}
DashboardViewmodel obj = new DashboardViewmodel();
return View("SalesVisit", obj);
}
When you use a GroupBy you get an IEnumerable<IGrouping<Key,YourOriginalType>> so you do not have .Employee and .VisitingID properties.
Change as following:
public class EmployeeCount
{
public string Employee {get; set;}
public int Count {get; set;}
}
List<EmployeeCount> result = db.View_VisitorsForm
.Where(item => item.VisitingDate >= beginDate && item.VisitingDate < endDate)
.GroupBy(G => G.Employee)
.Select(e =>new EmployeeCount
{
employee = e.Key,
count = e.Count()
}).ToList();
//Now add the result to the object you are passing to the View
Also keep in mind that you are not instantiating objects of type View_VisitorsForm but an anonymous object so assigning the result to empcount yet alone with the added FirstOrDefault will not compile
To pass this structure to the View and present it check this question
hope this helps you
var query = db.View_VisitorsForm.Where(o => o.VisitingDate >= new DateTime(2016,10,01) && o.VisitingDate <= new DateTime(2016, 10, 30)).GroupBy(G => G.Employee)
foreach (var item in query)
{
Console.WriteLine($"Employee Id {item.Key} : Count :{item.Count()}");
}
I have the below class and linq query I am using to populate a grid!
The Title is the same for every row returned. What I am trying to do is populate mString with the distinct Title from the query so I can bind it to a seperate textblock.
I probably didnt need to show all the code, but maybe it will help. How can I show the distinct Title.
public class Items
{
public int Id { get; set; }
public string Details { get; set; }
public string Title { get; set; }
public int NewNumber { get; set; }
}
private ObservableCollection<Items> mItem = new ObservableCollection<Items>();
private string mString = string.Empty;
public string SpecTitle
{
get { return mString; }
}
public ObservableCollection<Items> GetItems
{
get { return mItem; }
}
Here is the linq query
var results = (from z in mContext.View
orderby z.ItemNumber ascending
where z.ItemId == mId
select new Items()
{
Id = z.ItemId,
Details = z.Details,
Title = z.ItemTitle,
NewNumber = z.ItemNumber
});
List<Items> mNewItems = results.ToList();
mItem.Clear();
mNewItems.ForEach(y => mItem.Add(y));
var titleList = mNewItems.Select(i => i.Title).Distinct().ToList();
Converting my comment into an answer:
just do Items.Select(x => x.Title).Distinct();.
There is an additional library called moreLinq https://code.google.com/p/morelinq/ that has an extenction distinctby that you can you to distinct based on the given key.
it would as simle as this
var results = (from z in mContext.View
orderby z.ItemNumber ascending
where z.ItemId == mId
select new Items()
{
Id = z.ItemId,
Details = z.Details,
Title = z.ItemTitle,
NewNumber = z.ItemNumber
}).DistinctBy(c=>c.Title).ToList();
You can implement your custom comparer for distinct:
public class ItemsComparer : IEqualityComparer<Items>
{
public bool Equals(Items x, Items y)
{
return x.Title == y.Title;
}
public int GetHashCode(Items obj)
{
return obj.Title.GetHashCode();
}
}
then just use
var titleList = mNewItems.Distinct(new ItemsComparer()).Select(t=>t.Items);
I have two DTOs:
public class MasterDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<DetailDTO> Details { get; set; }
}
public class DetailDTO
{
public int Id { get; set; }
public string DetailName { get; set; }
}
Also, I have a function:
using (var context = new Context())
{
var r = context.MasterData
.Select(d => new MasterDTO
{
Id = d.Id,
Name = d.Name,
}
}
I need to fill the list of DetailDTOs too and do it in a single request.
At this moment, I have to get list of DetailsData data and add it through foreach to the MasterDTO, which, of course causes a lot of requests to the database server.
Is there a better solution?
In your data call, do an eager load on your DetailData.
Example:
var r = context.MasterData.Include("DetailData")
DetailData should be the name of your navigation property attached to your MasterData entity.
This will cause detail data to be pulled along with your call for MasterData.
The full call may look something like this:
using (var context = new Context())
{
context.LazyLoadingEnabled = false;
var r = context.MasterData.Include("DetailData")
.Select(d => new MasterDTO()
{
Id = d.Id,
Name = d.Name,
Details = d.Details.Select(dt => new DetailDTO()
{
Id = dt.Id,
DetailName = dt.DetailName
})
});
}
I hope it's more clear what I want to do from the code than the title. Basically I am grouping by 2 fields and want to reduce the results into a collection all the ProductKey's constructed in the Map phase.
public class BlockResult
{
public Client.Names ClientName;
public string Block;
public IEnumerable<ProductKey> ProductKeys;
}
public Block()
{
Map = products =>
from product in products
where product.Details.Block != null
select new
{
product.ClientName,
product.Details.Block,
ProductKeys = new List<ProductKey>(new ProductKey[]{
new ProductKey{
Id = product.Id,
Url = product.Url
}
})
};
Reduce = results =>
from result in results
group result by new {result.ClientName, result.Block} into g
select new BlockResult
{
ClientName = g.Key.ClientName,
Block = g.Key.Block,
ProductKeys = g.SelectMany(x=> x.ProductKeys)
};
}
I get some weird System.InvalidOperationException and a source code dump where basically it is trying to initialize the list with an int (?).
If I try replacing the ProductKey with just IEnumerable ProductIds (and make appropriate changes in the code). Then the code runs but I don't get any results in the reduce.
You probably don't want to do this. Are you really going to need to query in this manner? If you know the context, then you should probably just do this:
var q = session.Query<Product>()
.Where(x => x.ClientName == "Joe" && x.Details.Block == "A");
But, to answer your original question, the following index will work:
public class Products_GroupedByClientNameAndBlock : AbstractIndexCreationTask<Product, Products_GroupedByClientNameAndBlock.Result>
{
public class Result
{
public string ClientName { get; set; }
public string Block { get; set; }
public IList<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public string Id { get; set; }
public string Url { get; set; }
}
public Products_GroupedByClientNameAndBlock()
{
Map = products =>
from product in products
where product.Details.Block != null
select new {
product.ClientName,
product.Details.Block,
ProductKeys = new[] { new { product.Id, product.Url } }
};
Reduce = results =>
from result in results
group result by new { result.ClientName, result.Block }
into g
select new {
g.Key.ClientName,
g.Key.Block,
ProductKeys = g.SelectMany(x => x.ProductKeys)
};
}
}
When replicating I get the same InvalidOperationException, stating that it doesn't understand the index definition (stack trace omitted for brevity).
Url: "/indexes/Keys/ByNameAndBlock"
System.InvalidOperationException: Could not understand query:
I'm still not entirely sure what you're attempting here, so this may not be quite what you're after, but I managed to get the following working. In short, Map/Reduce deals in anonymous objects, so strongly typing to your custom types makes no sense to Raven.
public class Keys_ByNameAndBlock : AbstractIndexCreationTask<Product, BlockResult>
{
public Keys_ByNameAndBlock()
{
Map = products =>
from product in products
where product.Block != null
select new
{
product.Name,
product.Block,
ProductIds = product.ProductKeys.Select(x => x.Id)
};
Reduce = results =>
from result in results
group result by new {result.Name, result.Block}
into g
select new
{
g.Key.Name,
g.Key.Block,
ProductIds = g.SelectMany(x => x.ProductIds)
};
}
}
public class Product
{
public Product()
{
ProductKeys = new List<ProductKey>();
}
public int ProductId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public string Block { get; set; }
public IEnumerable<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public int Id { get; set; }
public string Url { get; set; }
}
public class BlockResult
{
public string Name { get; set; }
public string Block { get; set; }
public int[] ProductIds { get; set; }
}