Refactor methods - pass in property name - c#

I'm wondering if it's possible to refactor these two methods into one. The only difference is in the Select method; one uses BaselineSetNumber, the other ComparisonSetNumber.
public Set LoadBaselineSet(ObservableCollection<Set> sets)
{
using (var db = _contextFactory.GetContext())
{
var setNumber =
db.Users.Where(x => x.Login == Environment.UserName)
.Select(x => x.BaselineSetNumber).Single(); // !!! HERE
return sets.Single(x => x.SetNumber == setNumber);
}
}
public Set LoadComparisonSet(ObservableCollection<Set> sets)
{
using (var db = _contextFactory.GetContext())
{
var setNumber =
db.Users.Where(x => x.Login == Environment.UserName)
.Select(x => x.ComparisonSetNumber).Single(); // !!! HERE
return sets.Single(x => x.SetNumber == setNumber);
}
}
I'd like to have a method that I can call like LoadSet(sets, BaselineSetNumber); or LoadSet(sets, ComparisonSetNumber);

Yes, this is possible by creating a higher-order function. Your new code would look something like this:
public Set LoadBaselineSet(ObservableCollection<Set> sets)
{
return LoadSet(sets, (x) => x.BaselineSetNumber)
}
public Set LoadComparisonSet(ObservableCollection<Set> sets)
{
return LoadSet(sets, (x) => x.ComparisonSetNumber)
}
public Set LoadSet(ObservableCollection<Set> sets, Func<dbObject, Int> elementIdentity){
using (var db = _contextFactory.GetContext())
{
var setNumber =
db.Users.Where(x => x.Login == Environment.UserName)
.Select(elementIdentity).Single(); // !!! HERE
return sets.Single(x => x.SetNumber == setNumber);
}
}

Related

Efficiently select a set of objects that have multi value keys

I have a ProductVersions model which has a multi part key, a int ProductId and a int VersionNum field.
The function below takes a list of simple Dto classes that are just these 2 fields with goal of returning a set full ProductVersion objects from the database that match.
Below is a less than efficient solution. I am expecting the incoming list to only between 2 to 4 items so its not too bad but I'd like to do better.
private async Task<List<ProductVersion>?> GetProductVersionsFromDto(IList<ProductVersionDto>? productVersionDtos)
{
List<ProductVersion>? productVersions = null;
if (productVersionDtos != null)
{
foreach (ProductVersionDto dto in productVersionDtos)
{
ProductVersion? productVersion = await myPortalDBContext.ProductVersions
.Where(pv => pv.ProductId == dto.ProductId && pv.VersionNum == dto.VersionNum)
.FirstOrDefaultAsync();
if (productVersion != null)
{
if (productVersions == null) productVersions = new List<ProductVersion>();
productVersions.Add(productVersion);
}
}
}
return productVersions;
}
I had consider something like this:
private async Task<List<ProductVersion>?> GetProductVersionsFromDto(IList<ProductVersionDto>? productVersionDtos)
{
List<ProductVersion>? productVersions = null;
if (productVersionDtos != null)
{
productVersions = await myPortalDBContext.ProductVersions
.Join(productVersionDtos,
pv => new { pv.ProductId, pv.VersionNum },
pvd => new { pvd.ProductId, pvd.VersionNum },
(pv, pvd) => pv)
.ToListAsync();
}
return productVersions;
}
but at runtime fails because the Join doesn't make sense. Anyone know of way to do this more efficiently with just a single round-trip into the dbContext?
Use FilterByItems extension and then you can generate desired query:
private async Task<List<ProductVersion>?> GetProductVersionsFromDto(IList<ProductVersionDto>? productVersionDtos)
{
if (productVersionDtos == null)
return null;
var productVersions = await myPortalDBContext.ProductVersions
.FilterByItems(productVersionDtos,
(pv, dto) => pv.ProductId == dto.ProductId && pv.VersionNum == dto.VersionNum, true)
.ToListAsync();
return productVersions;
}

comparing current list data with old list data

I have to compare current list of data with previous list of data. In my list class i have
Id,
Comment,
Updatedby,
Updated Dt,
IsEdited
and few other fields. I am comparing like below.
foreach (var cscData in Currentcloses)
{
if (cscData.Status == ReferenceEnums.ActionStatus.EDIT)
{
if (Previoussoftcloses != null)
{
foreach (var pscData in Previouscloses)
{
if (cscData.Id == pscData.Id)
{
//my logic goes here
}
}
}
}
}
Is there any better way other than this. Just want to check.
New Code
var currentData = Currentsoftcloses
.Where(c => c.Status == ReferenceEnums.ActionStatus.EDIT);
foreach (var cscData in currentData)
{
if (Previoussoftcloses != null)
{
var previous = Previoussoftcloses
.GroupBy(item => item.Id)
.ToDictionary(chunk => chunk.Key, chunk => chunk.First());
if (previous.TryGetValue(cscData.Id, out var pscData))
{
//my logic goes here
}
} }
You can get rid of inner loop; if Previouscloses is long, your code will be faster: O(|Previoussoftcloses| + |Currentcloses|) versus O(|Previoussoftcloses| * |Currentcloses|) time complexity.
// If Previoussoftcloses == null we can do nothing, let's check for this possibility
if (Previoussoftcloses != null) {
// Dictionary is faster then List on Contains O(1) vs. O(N)
var previous = Previouscloses
.GroupBy(item => item.Id)
.ToDictionary(chunk => chunk.Key, chunk => chunk.First());
// Readability: what we are going to scan
var current = Currentcloses
.Where(c => c.Status == ReferenceEnums.ActionStatus.EDIT);
foreach (var cscData in current) {
if (previous.TryGetValue(cscData.Id, out var pscData)) {
//my logic goes here
}
}
}

How to assign "var" inside if statement

I need to do this:
var productsLocation = response.blah blah; //with linq query
var item; // even var item = null; //not valid
if(condition){
item = productsLocation.linq query
} else {
item = productsLocation.differentquery
}
var group = item.query;
Is this possible? If yes, how?
EDIT: here is my exact code:
var productLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
var items;
if (condition)
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
} else {
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}
If you look closely at the logic, you notice you don't actually even need the if block. The whole thing can be written in one expression as follows:
var items = productLocation
.Select(s => new ProductClass(s))
.Where(s => categories.Contains(s.CategoryName) && (condition || stocks.Contains(s.Barcode)));
First of all get your response variable type, then initialize 'item' variable as IEnumarable where T is same as response variable type
var productsLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
IEnumerable<ProductClass> item;
if (condition)
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
}
else
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}
var group = item.Where(condition);
You can do it with IEnumerable interface in this way:
using System.Collections;
using System.Collections.Generic;
List<string> products = new List<string>() { "First", "Second", "Third", "Fourth" };
IEnumerable item;
var condition = false;
if (condition)
{
item = products.Select(x=>x);
}
else
{
item = products.Where(x => x.StartsWith("F"));
}
var group = item.Cast<string>().Where(/*...Here your conditions...*/)

How to replace normal foreach to linq ForEach?

public static List<TDuplicate> ValidateColumnInList<TItem, TDuplicate>(List<TDuplicate> DuplicateExpression) where TDuplicate : DuplicateExpression
{
List<TDuplicate> TempDuplicateExpression = new List<TDuplicate>();
var itemProperties = typeof(TItem).GetProperties();
foreach (var DplExpression in DuplicateExpression)
{
bool IsContainColumn = itemProperties.Any(column => column.Name == DplExpression.ExpressionName);
if (!IsContainColumn)
{
TempDuplicateExpression.Add(DplExpression);
}
}
return TempDuplicateExpression;
}
In the above section how to replace above foreach to linq ForEach.
You do not need foreach or ForEach here. Below code should give you result:
var itemProperties = typeof(TItem).GetProperties();
List<TDuplicate> tempDuplicateExpression = DuplicateExpression
.Where(m => !itemProperties.Any(column => column.Name == m.ExpressionName))
.ToList();
return tempDuplicateExpression;
You can get result by this simple way:
var result = DuplicateExpression.Where(n=>!itemProperties.Any(column => column.Name == n.ExpressionName)).ToList();
Or you can user ForEach like this:
DuplicateExpression.ForEach(n=>
{
bool IsContainColumn = itemProperties.Any(column => column.Name == n.ExpressionName);
if (!IsContainColumn)
{
TempDuplicateExpression.Add(n);
}
}
)

entity framework 5 MaxLength

I was using EF4 and a piece of code I found to get the MaxLength value from an entity like this:
public static int? GetMaxLength(string entityTypeName, string columnName)
{
int? result = null;
using (fooEntities context = new fooEntities())
{
Type entType = Type.GetType(entityTypeName);
var q = from meta in context.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.Name == columnName
&& p.TypeUsage.EdmType.Name == "String")
select p;
var queryResult = q.Where(p =>
{
bool match = p.DeclaringType.Name == entityTypeName;
if (!match && entType != null)
{
match = entType.Name == p.DeclaringType.Name;
}
return match;
}).Select(sel => sel.TypeUsage.Facets["MaxLength"].Value);
if (queryResult.Any())
{
result = Convert.ToInt32(queryResult.First());
}
return result;
}
}
However, I upgraded to EF5 and I know get this error message:
...fooEntities' does not contain a definition for 'MetadataWorkspace' and no
extension method 'MetadataWorkspace' accepting a first argument of type
'...fooEntities' could be found (are you missing a using directive or an assembly
reference?)
What's the best way to get that meta data from EF5?
This is a very handy piece of code. I refactored it a bit and it's so useful I thought I would post it here.
public static int? GetMaxLength<T>(Expression<Func<T, string>> column)
{
int? result = null;
using (var context = new EfContext())
{
var entType = typeof(T);
var columnName = ((MemberExpression) column.Body).Member.Name;
var objectContext = ((IObjectContextAdapter) context).ObjectContext;
var test = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace);
if(test == null)
return null;
var q = test
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
.SelectMany(meta => ((EntityType) meta).Properties
.Where(p => p.Name == columnName && p.TypeUsage.EdmType.Name == "String"));
var queryResult = q.Where(p =>
{
var match = p.DeclaringType.Name == entType.Name;
if (!match)
match = entType.Name == p.DeclaringType.Name;
return match;
})
.Select(sel => sel.TypeUsage.Facets["MaxLength"].Value)
.ToList();
if (queryResult.Any())
result = Convert.ToInt32(queryResult.First());
return result;
}
}
And you can call it like:
GetMaxLength<Customer>(x => x.CustomerName);
This is assuming you've got a DbSet defined in your DbContext of type Customer, which has a property of CustomerName with a defined MaxLength.
This is very helpful for things like creating Model attributes that set a textbox's maxlength to the max length of the field in the database, always ensuring the two are the same.
I refactored mccow002's example into a copy-paste-ready Extension method class:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Metadata.Edm;
public static class DbContextExtensions
{
// get MaxLength as an extension method to the DbContext
public static int? GetMaxLength<T>(this DbContext context, Expression<Func<T, string>> column)
{
return (int?)context.GetFacets<T>(column)["MaxLength"].Value;
}
// get MaxLength as an extension method to the Facets (I think the extension belongs here)
public static int? GetMaxLength(this ReadOnlyMetadataCollection<Facet> facets)
{
return (int?)facets["MaxLength"].Value;
}
// just for fun: get all the facet values as a Dictionary
public static Dictionary<string,object> AsDictionary(this ReadOnlyMetadataCollection<Facet> facets) {
return facets.ToDictionary(o=>o.Name,o=>o.Value);
}
public static ReadOnlyMetadataCollection<Facet> GetFacets<T>(this DbContext context, Expression<Func<T, string>> column)
{
ReadOnlyMetadataCollection<Facet> result = null;
var entType = typeof(T);
var columnName = ((MemberExpression)column.Body).Member.Name;
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var test = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace);
if (test == null)
return null;
var q = test
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
.SelectMany(meta => ((EntityType)meta).Properties
.Where(p => p.Name == columnName && p.TypeUsage.EdmType.Name == "String"));
var queryResult = q.Where(p =>
{
var match = p.DeclaringType.Name == entType.Name;
if (!match)
match = entType.Name == p.DeclaringType.Name;
return match;
})
.Select(sel => sel)
.FirstOrDefault();
result = queryResult.TypeUsage.Facets;
return result;
}
}
It means that you have not only upgraded EF but you have also changes the API. There are two APIs - the core ObjectContext API and simplified DbContext API. Your code is dependent on ObjectContext API (the only API available in EF4) but EF5 uses DbContext API (added in separate EntityFramework.dll assembly since EF4.1). If you want to use new EF features and your previous code you should just upgrade to .NET 4.5.
If you also want to use a new API you will have to update a lot of your existing code but it is still possible to get ObjectContext from DbContext and make your method work again. You just need to use this snippet:
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
and use objectContext instead of context in your code.
I had similar issue and solution is here;
MyDBEntities ctx = new MyDBEntities();
var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
var cols = from meta in objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.DeclaringType.Name == "TableName")
select new
{
PropertyName = p.Name
};

Categories