I'm starting with Livecharts2 (I did not try previous versions) and I'm not sure how to bind data with Entity Framework.
I need to display a chart with warehouse name and the quantity of access of each.
This is what I already have:
List<Access> access = context.Access.ToList();
var countAccess = access
.GroupBy(acc => acc.IdWarehouse)
.Select(group => new
{
Warehouse = group.Key,
Quantity = group.Count()
});
List<int> listQt = new List<int>();
List<int> list_warehouses = new();
foreach (var item in countAccess)
{
listQt.Add(item.Quantity);
list_warehouses.Add(item.Warehouse);
}
cartesianChart1.Series = new ISeries[]
{
new LineSeries<int>
{
Values = listQt,
Name = "Quantity"
},
new ColumnSeries<int>
{
Values = list_warehouses,
Name = "Warehouse"
}
};
My model classes:
public partial class Access
{
public int IdAccess { get; set; }
public byte IdWarehouse { get; set; }
}
public partial class Warehouse
{
public byte IdWarehouse { get; set; }
public string Name{ get; set; } = null!;
}
This code works with the IdWarehouse but Name, is there a better way to do it, instead of creating new list, foreach etc? I'm not sure if it is unnecessary
I tried with List<string> to get the warehouse's names, but got an exception cause is not implemented yet by creator/s
Related
Good afternoon, I am looking to transfer a list of objects that implement a certain interface ("IRecord"), what I do is to filter in a new list the objects that implement the interface in the following case "IEntry", until there is no problem, however, I have problems when I try to caste the filtered list to the type "IList" to use the properties that this last one has, this produces an exception, how can I solve this, Is there a way to avoid going through the whole list, and create a new one again?
interface IRecord
{
string Details { get; set; }
}
interface IEntry : IRecord
{
decimal TotalValue { get; set; }
}
interface IEgress : IRecord
{
string Type { get; set; }
}
class Entry : IEntry
{
public string Details { get; set; }
public decimal TotalValue { get; set; }
public void Foo() { }
}
class Egress : IEgress
{
public string Details { get; set; }
public string Type { get; set; }
}
This is the code I am trying to execute
var records = new List<IRecord>() { new Entry() { Details = "foo" }, new Egress() { Details = "bar" } };
var filteredList = records.Where(entry => entry is Entry).ToList();
var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);
As already mentioned in comments you can Cast your query before calling ToList()
var filteredList = records.Where(entry => entry is Entry).Cast<IEntry>().ToList();
So the end result would be
var records = new List<IRecord>()
{
new Entry() { Details = "foo", TotalValue = 12 },
new Egress() { Details = "bar" }
};
var filteredList = records.Where(entry => entry is Entry).Cast<IEntry>().ToList();
var sum = (IList<IEntry>)filteredList;
var x = sum.Sum(en => en.TotalValue);
I added a value to your Entry type too, which then allows you to prove your code works :D
Here is a link to Microsoft document on inheritance
I am trying to group a column and form the the rest of the columns as child, hierarchical data:
I am trying to group by Code and form the parent and child relationship from a flat list, below is the hierarchical data I am trying to form:
source list:
public class ItemAssignmentFlatList
{
public int Code { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public int ItemCode{ get; set; }
public DateTime EffectiveDate{ get; set; }
public string Area{ get; set; }
public string TaxCode{ get; set; }
public string LocationId { get; set; }
}
Need to convert above flat list into below List of hierarchical data:
public class ItemInfo
{
public int Code { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public List<TaxInfo> TaxPlan { get; set; }
}
public class TaxPlan
{
public int ItemCode{ get; set; }
public DateTime EffectiveDate{ get; set; }
public string Area{ get; set; }
public string TaxCode{ get; set; }
public string LocationId { get; set; }
}
Need hierarchical list with above flat data list with C# extension methods.
I have below code, but looking for clean code to reduce number of lines:
var items= results.GroupBy(x => new { x.Code, x.Type });
List<ItemInfo> result = new List<ItemInfo>();
foreach (var group in items)
{
var taxPlans = group.
Select(y => new TaxPlan
{
TaxArea = y.TaxArea,
ItemCode = y.ItemCode
});
var itemInfo= new ItemInfo
{
Code = group.FirstOrDefault().Code,
Type = group.FirstOrDefault().Type,
Description = group.FirstOrDefault().Description,
TaxPlan = taxPlans.ToList()
};
result.Add(itemInfo);
}
Something like this?:
var input = new List<ItemAssignmentFlatList>(){
new ItemAssignmentFlatList{
Code = 1,
Area = "a"
},
new ItemAssignmentFlatList{
Code = 1,
Area = "b"
},
new ItemAssignmentFlatList{
Code = 2,
Area = "c"
}
};
input
.GroupBy(
x => x.Code,
(int code, IEnumerable<ItemAssignmentFlatList> items) =>
{
var first = items.FirstOrDefault();
var key = new ItemInfo
{
Code = first.Code
//, ...
};
var plan = items.
Select(y => new TaxPlan
{
Area = y.Area
//, ...
});
return new
{
key = key,
items = plan
};
}
).Dump();
Whenever you have a sequence of similar object, and you want to make "Items with their SubItems", based on common properties in your source sequence, consider to use one of the overloads of Enumerable.GroupBy
Because you don't just want "Groups of source items" but you want to specify your output, consider to use the overload that has a parameter resultSelector.
parameter keySelector: what should all elements in a group have in common
parameter resultSelector: use the common thing, and all elements that have this common thing to make one output element.
.
IEnumerable<ItemAssignmentFlatList> flatItemAssignments = ...
IEnumerable<ItemInfo> items = flatItemAssignments
// make groups with same {Code, Type, Description}
.GroupBy(flatItemAssignment => new {Code, Type, Description},
// parameter resultSelector: take the common CodeTypeDescription,
// and all flatItemAssignments that have this common value
// to make one new ItemInfo
(codeTypeDescription, flatItemAssignmentsWithThisCodeTypeDescription) => new ItemInfo
{
Code = codeTypeDescription.Code,
Type = codeTypeDescription.Type,
Description = codeTypeDescription.Description,
TaxPlans = flatItemAssignmentsWithThisCodeTypeDescription
.Select(flatItemAssignment => new TaxPlan
{
ItemCode = flatItemAssignment.ItemCode,
EffectiveDate = flatItemAssignment.EffectiveDate,
Area = flatItemAssignment.Area,
...
})
.ToList(),
});
Using RavenDB v4.2 or higher, I want to setup an index that queries another collection. Basically, reproduce a WHERE IN clause in the mapping part of the index.
The models below represent two collections. Here each User has a collection of Device ID's:
class Device {
public string Id { get; set; }
public string Name { get; set; }
}
class User {
public string Id { get; set; }
public string BlogPostId { get; set; }
public List<string> DeviceIds { get; set; }
}
Now consider the following index as an example on what I'm trying to achieve:
public class DeviceIndex : AbstractIndexCreationTask<Device, DeviceIndex.Result>
{
public class Result
{
public string Id { get; set; }
public string DeviceName { get; set; }
public bool HasUser { get; set; }
public int UserCount { get; set; }
}
public DeviceIndex()
{
Map = devices => from d in devices
select new Result
{
Id = d.Id,
DeviceName = d.Name,
HasUser = ... ?, // How to get this from Users collection?
UserCount = ... ? // same...
};
}
How do I fill the HasUser true/false and UserCount properties in this index? E.g. how can I query the 'User' collection here?
Please note that this example is seriously simplified for brevity. I'm not so much interested in workarounds, or changing the logic behind it.
As #Danielle mentioned you need to use a mutli-map-index and reduce the result.
Here is a working example
public class DeviceIndex : AbstractMultiMapIndexCreationTask<DeviceIndex.Result>
{
public class Result
{
public string Id { get; set; }
public string DeviceName { get; set; }
public bool HasUser { get; set; }
public int UserCount { get; set; }
}
public DeviceIndex()
{
AddMap<User>(users => from u in users
from deviceId in u.DeviceIds
let d = LoadDocument<Device>(deviceId)
select new Result
{
Id = d.Id,
HasUser = true,
UserCount = 1,
DeviceName = d.Name,
});
AddMap<Device>(devices => from d in devices
select new Result
{
Id = d.Id,
HasUser = false,
UserCount = 0,
DeviceName = d.Name,
});
Reduce = results => from result in results
group result by new { result.Id } into g
select new Result
{
Id = g.First().Id,
DeviceName = g.First().DeviceName,
HasUser = g.Any(e => e.HasUser),
UserCount = g.Sum(e => e.UserCount),
};
}
}
and you can call it like this
var result = await _session.Query<DeviceIndex.Result, DeviceIndex>().ToListAsync();
If you would have a Users List in the Device class List<string> Users
a list that contains the document ids from the Users collection then you could Index these Related documents.
See:
https://demo.ravendb.net/demos/csharp/related-documents/index-related-documents
Or do the opposite,
Create an index on the Users collection, and index the related Device info
Without changing current models,
You can create a Multi-Map Index to index data from different collections.
https://ravendb.net/docs/article-page/4.2/csharp/indexes/multi-map-indexes
https://ravendb.net/docs/article-page/4.2/csharp/studio/database/indexes/create-multi-map-index
https://ravendb.net/learn/inside-ravendb-book/reader/4.0/10-static-indexes-and-other-advanced-options#querying-many-sources-at-once-with-multimap-indexes
I have a dynamic table in my Web Application (written with angualrjs), in this table you can add columns / add rows and etc..
I want to keep this table/s stored in a database using entity framework.. I save this table to the server as a List[] (Array of List of strings - each List in the array represent a row in the table).
But entity framework requires me to create a model.. but the probelm is the table is completely dynamic.... (users can Add/Remove Rows/Columns dynamicly..)
How can I achieve storing a List[] in a data table with entity
framework?
Thanks alot for the help!!!
Or is there a better way of implementing this?
If you want to model it in terms of EF/DB modelling, you can do 2 things(very basic)
Standard one to many relationship between a row and columns.
One row with id and values column, where the values column is just a comma separated list.
In the example below DynamicData and DynamicDataValue are example of 1-many relationship and DynamicData2 is comma separated list
The EF Context
public class Context : DbContext
{
public Context()
: base("35213027DatatableFromArraylist"){}
public DbSet<DynamicData> DynamicDatas { get; set; }
public DbSet<DynamicData2> DynamicData2s { get; set; }
}
1-many
public class DynamicData
{
public int Id { get; set; }
public virtual ICollection<DynamicDataValue> Values { get; set; }
}
public class DynamicDataValue
{
public int Id { get; set; }
public string Value { get; set; }
}
Comma Seperated
public class DynamicData2
{
public int Id { get; set; }
public string Values { get; set; }
}
Saving and Reading
static void Main(string[] args)
{
//one-many
using (var context = new Context())
{
var values = new List<DynamicDataValue>();
for (int i = 0; i < 11; i++)
{
values.Add(new DynamicDataValue { Value = string.Format("Value{0}", i) });
}
context.DynamicDatas.Add(new DynamicData { Values = values });
context.SaveChanges();
var query =
context.DynamicDatas.Select(
data => new { data.Id, values = data.Values.Select(value => value.Value) }).ToList();
foreach (var item in query)
{
var strings = item.values.Aggregate((s, s1) => string.Format("{0},{1}", s, s1));
Console.WriteLine("{0} - {1}", item.Id, strings);
}
}
Console.ReadLine();
//comma seperated
using (var context = new Context())
{
var values = new List<string> { "value1", "value2", "value3" };
context.DynamicData2s.Add(new DynamicData2 { Values = values.Aggregate((s, s1) => string.Format("{0},{1}", s, s1)) });
context.SaveChanges();
var data = context.DynamicData2s.ToList();
foreach (var dynamicData2 in data)
{
Console.WriteLine("{0}-{1}", dynamicData2.Id, dynamicData2.Values);
}
}
}
I have a class that I made and I want to use it for a list but when I try adding data to it and loop through the list all I'm getting is the address of the class. I have no idea why its added that as the values.
My Class is
public class Regions
{
public int dataID { get; set; }
public int documentID { get; set; }
public string region_ID { get; set; }
public string region_Name { get; set; }
public string sortID { get; set; }
}
This is how I am trying to add the values. The query has the right data in it, but the list isn't getting the data, just where the class resides.
List<Regions> lst = new List<Regions>();
var q = dt.AsEnumerable()
.Select(region => new {
dataID = region.Field<int>("dataID"),
documentID = region.Field<int>("documentID"),
region_ID = region.Field<string>("Region_ID"),
region_Name = region.Field<string>("Region_Name"),
sortID = region.Field<string>("SortID").ToString()
});
foreach (var d in q)
lst.Add(new Regions() { dataID = d.dataID,
documentID = d.documentID,
region_ID = d.region_ID,
region_Name = d.region_Name,
sortID = d.sortID
});
EDIT
Here is a link that I found that is similar what I am trying to do, but it doesn't seem he had the same errors as I did. I tried that answer, but wasn't working for me.
Storing data into list with class
Fixed
When I was looping through the list, I wasn't reading it properly.
Try adding this in Regions
public override string ToString()
{
return region_Name;
}
actually you can create the list in one step
List<Regions> lst = dt.Rows.OfType<DataRow>().Select(region => new Regions{
dataID = region.Field<int>("dataID"),
documentID = region.Field<int>("documentID"),
region_ID = region.Field<string>("Region_ID"),
region_Name = region.Field<string>("Region_Name"),
sortID = region.Field<string>("SortID")
}).ToList();