DefaultIfEmpty for LINQ to a DataTable? - linq

I have a LINQ query written to pull at least one row from a datatable as follows:
var generalQuery =
from contact in contacts.AsEnumerable().DefaultIfEmpty()
where contact.Field<String>("CONTACT_TYPE").ToUpper() == "AGENT"
select new
{
AgentName = contact.Field<String>("FIRST_NAME") + " " +
contact.Field<String>("LAST_NAME"),
AgentPhoneNumber = contact.Field<String>("PHONE"),
AgentEmailAddress = contact.Field<String>("EMAIL")
};
I then try to set the properties of a new instance of a class with the values in the LINQ query output:
var genInfo = new GeneralInformationType
{
AgentName = generalQuery.FirstOrDefault().AgentName,
AgentPhoneNumber = generalQuery.FirstOrDefault().AgentPhoneNumber,
AgentEmailAddress = generalQuery.FirstOrDefault().AgentEmailAddress
};
The problem I am running into is that occasionally there are no results in the query. This tries to set the value of the various strings in GeneralInformationType to null and causes exceptions. I tried various methods of DefaultIfEmpty, but can't figure out where to put it.
Any help would be appreciated.
Thanks,
Rob

I would recommend removing DefaultIfEmpty() in your generalQuery and adding some logic when generalQuery is empty like so:
var generalQuery =
from contact in contacts.AsEnumerable()
where contact.Field<String>("CONTACT_TYPE").ToUpper() == "AGENT"
select new
{
AgentName = contact.Field<String>("FIRST_NAME") + " " +
contact.Field<String>("LAST_NAME"),
AgentPhoneNumber = contact.Field<String>("PHONE"),
AgentEmailAddress = contact.Field<String>("EMAIL")
};
var genInfo = new GeneralInformationType
{
AgentName = generalQuery.Any() ? generalQuery.First().AgentName : "Default Name",
....
};

There are two separate problems here. First, DefaultIfEmpty is going to effectively give you a sequence with a null DataRow if the query doesn't return anything. That will then fail not when it tries to assign strings - but when in the Where clause. You're then also using FirstOrDefault which would normally return null if there are no matching entries.
I would personally remove DefaultIfEmpty call, and put all the defaulting in the code for genInfo:
var generalQuery =
from contact in contacts.AsEnumerable()
where contact.Field<String>("CONTACT_TYPE").ToUpper() == "AGENT"
select new
{
AgentName = contact.Field<String>("FIRST_NAME") + " " +
contact.Field<String>("LAST_NAME"),
AgentPhoneNumber = contact.Field<String>("PHONE"),
AgentEmailAddress = contact.Field<String>("EMAIL")
};
// Like using DefaultIfEmpty(...).First()
var result = generalQuery.FirstOrDefault() ??
new { AgentName = "Default",
AgentPhoneNumber = "Default",
AgentEmailAddress = "Default" };
var genInfo = new GeneralInformationType
{
AgentName = result.AgentName,
AgentPhoneNumber = result.AgentPhoneNumber,
AgentEmailAddress = result.AgentEmailAddress
};
Obviously change "Default" to whatever you want. If you have more specific requirements, please explain what you're trying to do and I'm sure we'll be able to accommodate them...

Related

IQueryable.Union/Concat in .net core 3

I want to add a dummy member to an IQueryable and came up with this solution:
IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll(); //DbSet<Geography>
var dummyGeographies = new Geography[] { new Geography { Id = -1, Name = "All" } }.AsQueryable();
var combinedGeographies = geographies.Union(dummyGeographies);
var test = combinedGeographies.ToList(); //throws runtime exc
But it throws the following exception:
Processing of the LINQ expression 'DbSet
.Union(EnumerableQuery { Geography, })' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.
How could I make it work?!
you can only union on data structure which are the same
IQueryable is only applicable if the query expression not been been expressed (ToList) before its run against db and you want the expression modifiable . aka nothing which which is not going to db as a query needs to be IQueryable (simple explanation better to research and understand this yourself)
List<Geography> geographies = _unitOfWork.GeographyRepository
.GetAll() //DbSet<Geography>
.Select(o => new Geography { Id = o.Id, Name = o.Name })
.ToList();
List<Geography> dummyGeographies = new List<Geography>() {
new Geography[] { new Geography { Id = -1, Name = "All" } }
};
var combinedGeographies = geographies.Union(dummyGeographies);
var test = combinedGeographies.ToList();
I was able to achieve it with the following code:
IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = o.Id, Name = o.Name });
IQueryable<Geography> dummyGeographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = -1, Name = "All" });
var combinedGeographies = geographies.Union(dummyGeographies);

Convert if and foreach statement to select and where in linq

How would I go about changing my if statement and foreach to something cleaner in linq using select and where.
I've tried to make the if statement into a where clause and then use the select query as a replacement for the Foreach loop but that seem to have type issues and wasn't working.
{
StripeConfiguration.ApiKey = _appSettings.StripeSecretKey;
var profile = await _userManager.FindByIdAsync(customerServiceID);
var stripeId = profile.StripeAccountId;
if (stripeId == null)
throw new ArgumentException("No associated Stripe account found.");
List<PaymentMethodDto> result = new List<PaymentMethodDto>();
var options = new PaymentMethodListOptions
{
Customer = stripeId,
Type = "card",
};
var service = new PaymentMethodService();
var payments = await service.ListAsync(options);
if (payments != null && payments.Data?.Count > 0)
{
payments.Data.ForEach((x) =>
{
result.Add(
new PaymentMethodDto
{
Brand = x.Card.Brand,
LastDigits = x.Card.Last4,
StripeToken = x.Id,
CustomerID = x.CustomerId
});
});
}
return result;
}
Just do a regular Select.
List<PaymentMethodDto> result = payments.Data.Select(x => new PaymentMethodDto
{
Brand = x.Card.Brand,
LastDigits = x.Card.Last4,
StripeToken = x.Id,
CustomerID = x.CustomerId
})
.ToList();
If payments.Data has nothing in it, this will give you an empty list, which is what you want.
If payments is null, you'll get an exception, which I think if you think about it really hard is probably what you really want in that case too. Why would .ListAsync() yield a null value?

Error in LINQ to Entities ToString()

I get this error in LINQ to Entities: LINQ to Entities does not recognize the method 'System.String ToString()' method.
How should I solve this common problem?
Note that FleetViewModel.DWTStart is a string and fleet.DWTStart is a nullable decimal.
var qry = from fleet in _entitiesContext.Fleets
select new FleetViewModel
{
FleetID = fleet.FleetID,
FleetName = fleet.FleetName,
DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
};
Thanks.
Basically you need to do the final part in-process, which you can force with AsEnumerable:
var qry = _entitiesContext.Fleets
.Select(fleet => new { fleet.FleetID,
fleet.FleetName,
fleet.DWTStart,
fleet.DWTEnd })
.AsEnumerable() // Do the rest in-process
.Select(fleet => new FleetViewModel {
FleetID = fleet.FleetID,
FleetName = fleet.FleetName,
DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
});
If there's nothing else in the entity apart from these four properties, you can skip the anonymous type to start with - it's really only there to avoid fetching data you don't need:
var qry = _entitiesContext.Fleets
.AsEnumerable() // Do the rest in-process
.Select(fleet => new FleetViewModel {
FleetID = fleet.FleetID,
FleetName = fleet.FleetName,
DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
});

Dynamic Linq to Datatable Derived Field

Is it possible to use Dynamic Linq to run a query similar to:
Select a, b, a + b as c
from MyDataTable
I have an application where the user can enter SQL statements, the results of these statements are then assigned to a DataTable. There is also the option to derive a field based on other fields. (e.g. user can say field C = a + b, or field D = A*B+10 etc).
Ideally I would like to do something similar to:
string myCalc = "Convert.ToDouble(r.ItemArray[14])+Convert.ToDouble(r.ItemArray[45])";
var parameters = from r in dt.AsEnumerable()
select (myCalc);
What I want to do in this example is add the value of column 14 to column 45 and return it. It's up to the user to decide what expression to use so the text in the select needs to be from a string, I cannot hard code the expression. The string myCalc is purely for demonstration purposes.
You could do that using a Dictionary, and a DataReader and Dynamic Queries. Here is an example based in part in Rob Connery's Massive ORM RecordToExpando:
void Main()
{
string connString = "your connection string";
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connString);
string statement = "SUM = EstimatedEffort + OriginalEstimate, Original = OriginalEstimate";
// Note: You should parse the statement so it doesn't have any updates or inserts in it.
string sql = "SELECT " + statement +" FROM Activities";
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
conn.Open();
using(conn)
{
var cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var dic = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
dic.Add(
reader.GetName(i),
DBNull.Value.Equals(reader[i]) ? null : reader[i]);
}
results.Add(dic);
}
}
foreach (var dicRow in results)
{
foreach (string key in dicRow.Keys)
{
Console.Write("Key: " + key + " Value: " + dicRow[key]);
}
Console.WriteLine();
}
}
Something like this:
void Main()
{
var dataTable = new DataTable();
dataTable.Columns.Add("a", typeof(double));
dataTable.Columns.Add("b", typeof(double));
dataTable.Rows.Add(new object[] { 10, 20 });
dataTable.Rows.Add(new object[] { 30, 40 });
string myCalc = "Convert.ToDouble(ItemArray[0]) + Convert.ToDouble(ItemArray[1])";
var query = dataTable.AsEnumerable().AsQueryable();
var result = query.Select(myCalc);
foreach (Double c in result)
{
System.Console.WriteLine(c);
}
}

Update using LINQ to SQL

How can I update a record against specific id in LINQ to SQL?
LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:
using(var ctx = new FooContext()) {
var obj = ctx.Bars.Single(x=>x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}
Or write an SP that does the same in TSQL, and expose the SP through the data-context:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
In the absence of more detailed info:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
DataClassesDataContext dc = new DataClassesDataContext();
FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);
fd.FatherName=txtFatherName.Text;
fd.FatherMobile=txtMobile.Text;
fd.FatherOccupation=txtFatherOccu.Text;
fd.MotherName=txtMotherName.Text;
fd.MotherOccupation=txtMotherOccu.Text;
fd.Phone=txtPhoneNo.Text;
fd.Address=txtAddress.Text;
fd.GuardianName=txtGardianName.Text;
dc.SubmitChanges();
I found a workaround a week ago. You can use direct commands with "ExecuteCommand":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.

Resources