How to change the entity to linq - c#

I want to change this code from entity to linq.
I always get the error "value cannot be null. parameter name: text"
how to fix that error
public ActionResult Search(SearchView search)
{
IEnumerable<Transaction> thunhaps = null, chitieus = null;
decimal totalTN = 0, totalCT = 0;
int userid = Convert.ToInt32(Session["userid"]);
//var trans = new List<Transaction>();
QuanLyChiTieuDataContext context = new QuanLyChiTieuDataContext();
List<Transaction> trans = new List<Transaction>();
if (search.MoTa != null)
search.MoTa = "";
if (search.TransType == "i" || search.TransType == "b")
{
thunhaps = from item in context.ThuNhaps
where item.UserID == userid
&& item.MoTa.Contains(search.MoTa)
&& item.Ngay.Value >= search.TuNgay &&
item.Ngay <= search.DenNgay
select new Transaction
{
Id = item.Inc_Id,
SoTien = (decimal)item.SoTien,
MoTa = item.MoTa,
GhiChu = item.GhiChu,
NgayGD = item.Ngay.Value,
TransType = "Income"
};
totalTN = thunhaps.Sum(t => t.SoTien);
//List<ThuNhap> thuNhaps = new List<ThuNhap>();
//var totalTNhap = thuNhaps.Sum(t => t.SoTien);
}
if (thunhaps != null)
trans.AddRange(thunhaps);
ViewBag.Difference = totalTN - totalCT;
return PartialView("SearchResult", trans);
}
I very hard to try the change but I failed`

When asking questions in StackOverflow you should be clearer.
A working sample would make a lot easier for anyone to help you.
That being said, you probably get the error because you are querying a recent created context object (and context.ThuNhaps is probably empty, and item.MoTa is null and item.Ngay is null, ...).
Now, I don't know if your question is about the error or "change the entity to linq", which I think you meant change the syntax of LINQ being used, from Query (Comprehension) Syntax to Lamda (Method) Syntax.
Something like:
thunhaps = context.ThuNhaps
.Where(item =>
item.UserID == userid
&& item.MoTa.Contains(search.MoTa)
&& item.Ngay.Value >= search.TuNgay
&& item.Ngay <= search.DenNgay)
.Select(item =>
new Transaction
{
Id = item.Inc_Id,
SoTien = (decimal)item.SoTien,
MoTa = item.MoTa,
GhiChu = item.GhiChu,
NgayGD = item.Ngay.Value,
TransType = "Income"
});

Related

LinqToDb: Rank is server-side method

I am trying to use linq2db.EntityFrameworkCore for some of its windowing functions, such as RANK().
Below is my implementation:
var abc = (from tl in _repo.Context.TransferLink
join tlt in _repo.Context.TransferLinkType on new { TLinkId = tl.TransferLinkTypeId, EType = "Deviance" } equals new { TLinkId = tlt.TransferLinkTypeId, EType = tlt.EnumTransferLinkType }
//let duplicateCount = _repo.Context.TransferLink.Where(tl1 => tl1.SecondaryTransferId != null && tl.SecondaryTransferId != null &&
//tl1.SecondaryTransferId == tl.SecondaryTransferId.Value).Count()
where
(allTransferIds.Contains(tl.PrimaryTransferId) || allTransferIds.Contains(tl.SecondaryTransferId)) &&
!tl.Archived
select new
{
TransferLinkId = tl.TransferLinkId,
TransferLinktypeId = tl.TransferLinkTypeId,
PrimaryTransferId = tl.PrimaryTransferId,
SecondaryTransferId = tl.SecondaryTransferId,
DuplicateCount = Sql.Ext.Count(tl.TransferLinkId)
.Over()
.PartitionBy(tl.SecondaryTransferId)
.ToValue()
UpdatedDate = tl.UpdatedDate,
RankVal = Sql.Ext.Rank()
.Over()
.PartitionBy(tl.TransferLinkTypeId, tl.SecondaryTransferId)
.OrderByDesc(tl.UpdatedDate)
.ThenBy(tl.TransferLinkId)
.ToValue()
}).ToList();
This code throws the exception:
Rank is server-side method
I have tried searching for a solution, but could not find any.
Any idea?
For using linq2db.EntityFrameworkCore you have to switch to library's LINQ provider. It can be done by simple ToLinqToDB() call.
var query = /* some EF Core query */
query = query.ToLinqToDB();
var result = query.ToList();

LINQ Lambda for create a list with info from 3 related tables

I am trying to create a ViewModel list with info from Receipt table and then if related info exist in Reason table retreive the last Description inserted (ReceiptId related) and add it (if not just pass null) to the ViewModel Receipt list (RejectDescription). Here's the DB model:
Database Model
I tryied many ways to achieve this, at the moment this is the code that partially works for me, i say partially because in RejectDescription saves the Reason.Description if it exist else just pass null and it's ok.
The main problem is when there's many Reason.Descriptions it doesn't return and save the last one inserted (the most recent, is the one that i am looking for). Here is my code:
[HttpPost]
public ActionResult ReceiptList(string Keyword)
{
using (SEPRETEntities DBC = new SEPRETEntities())
{
long UserId = (long)Session["Id"];
IEnumerable<Receipt> receipts = DBC.Receipts.Where(x => x.PersonId == UserId && x.Active == true).ToList();
#region Search
if (!string.IsNullOrEmpty(Keyword))
{
Keyword = Keyword.ToLower();
receipts = receipts.Where(x => x.Person.Name.ToLower().Contains(Keyword) ||
x.Person.MiddleName.ToLower().Contains(Keyword) ||
x.Person.LastName.ToLower().Contains(Keyword) ||
x.Person.Email.ToLower().Contains(Keyword) ||
x.Person.Enrollment.ToLower().Contains(Keyword) ||
x.Person.Career.ToLower().Contains(Keyword) ||
x.Payment.Name.ToLower().Contains(Keyword) ||
x.Payment.Price.ToString().ToLower().Contains(Keyword) ||
x.Method.Name.ToLower().Contains(Keyword) ||
x.Phase.Name.ToLower().Contains(Keyword) ||
x.TimeCreated.ToString().ToLower().Contains(Keyword) ||
x.Voucher.ToString().ToLower().Contains(Keyword)
);
}
#endregion
List<ReceiptVM> ReceiptList = receipts.Select(x => new ReceiptVM
{
Id = x.Id,
PaymentId = x.PaymentId,
Enrollment = x.Person.Enrollment,
Career = x.Person.Career,
PersonName = string.Concat(x.Person.Name, " ", x.Person.MiddleName, " ", x.Person.LastName),
Email = x.Person.Email,
PaymentName = x.Payment.Name,
MethodName = x.Method.Name,
Voucher = x.Voucher,
Image = x.Image,
PhaseId = x.Phase.Id,
PriceFormatted = x.Payment.Price.ToString("C"),
Active = x.Active,
TimeCreatedFormatted = x.TimeCreated.ToString(),
RejectDescription = x.Rejections.FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
}).ToList();
return PartialView("~/Views/Receipt/_SearchReceipt.cshtml", ReceiptList);
}
}
For you information i am kinda newbie working on C# and ASP.NET MVC.Not sure if there's a better way to achieve this or something, any advice or tip is pretty appreciated.
Thank you and sorry for my bad english
You have to order reject reasons by Id which will fetch recent reason like below :
RejectDescription = x.Rejections.OrderByDescending(x=>x.Reason.Id).FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
Or you can use LastOrDefault to get most recent one like below:
RejectDescription = x.Rejections.LastOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
List<ReceiptVM> ReceiptList = receipts.Select(x => new ReceiptVM
{
Id = x.Id,
PaymentId = x.PaymentId,
Enrollment = x.Person.Enrollment,
Career = x.Person.Career,
PersonName = string.Concat(x.Person.Name, " ", x.Person.MiddleName, " ", x.Person.LastName),
Email = x.Person.Email,
PaymentName = x.Payment.Name,
MethodName = x.Method.Name,
Voucher = x.Voucher,
Image = x.Image,
PhaseId = x.Phase.Id,
PriceFormatted = x.Payment.Price.ToString("C"),
Active = x.Active,
TimeCreatedFormatted = x.TimeCreated.ToString(),
RejectDescription = x.Rejections.OrderByDescending(x=>x.Reason.Id).FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
}).ToList();

Linq where clause using filter object

I have a piece of Linq that queries an EntityFramework context in my web controller and returns the result, as follows:
[HttpGet]
public IActionResult GetRoutingRules()
{
var query = (from rr in _context.RoutingRules
join dest in _context.RoutingZones on rr.DestinationZoneId equals dest.ZoneId
join origin in _context.RoutingZones on rr.OriginZoneId equals origin.ZoneId
join hub in _context.RoutingHub on rr.HubId equals hub.HubId
select new RoutingRulesDto(rr) { DestinationZoneName = dest.ZoneName, OriginZoneName = origin.ZoneName, HubName = hub.HubName });
return Ok(query);
}
I want a new method that will take a "filter" object, where I can narrow down the results of the above. My filter object looks like this:
public class RoutingSearchFilterDto
{
public int BrandId { get; set; }
public int? ServiceType { get; set; }
public long? OriginZoneId { get; set; }
public long? DestinationZoneId { get; set; }
public int? RuleRanking { get; set; }
public bool? IsRuleActive { get; set; }
}
The minimum info that needs to be set in this class is BrandId. All other properties are options in the filter.
I need to write a new controller method that will utilise this, something like:
[HttpPost("filtered")]
public IActionResult GetFilteredRoutingRules([FromBody] RoutingSearchFilterDto filter)
{
...
}
How do I linq query on properties that could potentially be null? Essentially, a dynamic query depending on the properties set in the filter object.
NOTE: I want this to affect the select statement that the EF runs, not just let EF get all the data, then filter the data set - the point of this is to make the db call more efficient.
Filter object might be sent where BrandId = 1, IsRuleActive = 1. Equally, it could be BrandId = 1, ServiceType = 3 (and therefore IsRuleActive is null so shouldn't be in the linq where clause).
I've tried this:
var param = (Expression.Parameter(typeof(RoutingRules), "rr"));
Expression combinedExpr = null;
if (filter.BrandId != null)
{
var exp = Expression.Equal(Expression.Property(param, "BrandId"), Expression.Constant(filter.BrandId));
combinedExpr = exp;
}
if (filter.DestinationZoneId != null)
{
var exp = Expression.Equal(Expression.Property(param, "DestinationZoneId"), Expression.Constant(filter.DestinationZoneId));
combinedExpr = (combinedExpr == null ? exp : Expression.AndAlso(combinedExpr, exp));
}
if (filter.OriginZoneId != null)
{
var exp = Expression.Equal(Expression.Property(param, "OriginZoneId"), Expression.Constant(filter.OriginZoneId));
combinedExpr = (combinedExpr == null ? exp : Expression.AndAlso(combinedExpr, exp));
}
if (filter.EshopServiceType != null)
{
var exp = Expression.Equal(Expression.Property(param, "EshopServiceType"), Expression.Constant(filter.EshopServiceType));
combinedExpr = (combinedExpr == null ? exp : Expression.AndAlso(combinedExpr, exp));
}
if (filter.IsRuleActive != null)
{
var exp = Expression.Equal(Expression.Property(param, "IsRuleActive"), Expression.Constant(filter.IsRuleActive, typeof(bool?)));
combinedExpr = (combinedExpr == null ? exp : Expression.AndAlso(combinedExpr, exp));
}
if (filter.RuleRanking != null)
{
var exp = Expression.Equal(Expression.Property(param, "RuleRanking"), Expression.Constant(filter.RuleRanking));
combinedExpr = (combinedExpr == null ? exp : Expression.AndAlso(combinedExpr, exp));
}
if (combinedExpr == null)
combinedExpr = Expression.Default(typeof(bool));
var compiled = Expression.Lambda<Func<RoutingRules, bool>>(combinedExpr, param).Compile();
var results = (from rr in _context.RoutingRules.Where(compiled)
join dest in _context.RoutingZones on rr.DestinationZoneId equals dest.ZoneId
join origin in _context.RoutingZones on rr.OriginZoneId equals origin.ZoneId
join hub in _context.RoutingHub on rr.HubId equals hub.HubId
where rr.BrandId == 21
select new RoutingRulesDto(rr) { DestinationZoneName = dest.ZoneName, OriginZoneName = origin.ZoneName, HubName = hub.HubName });
But the Where clause isn't applied to the generated Sql, it seems to pull back all records, then apply the where in memory, which isn't what I need.
Thanks in advance for any pointers!!
You can build an expression tree for this, but have you considered:
IQueryable<...> query = ...;
if (routingSearchFilter.ServiceType != null)
query = query.Where(e => e.ServiceType == routingSearchFilter.ServiceType);
if (...)
query = query.Where(....);
The EF engine is smart enough to combine the Where clauses (with AND of course).
Edit:
It wasn't clear if you wanted to filter on the joined result or only on the first table. In that case it would continue like
var result = (from rr in query
join dest in _context.RoutingZones on rr.DestinationZoneId equals dest.ZoneId
join ...
select new RoutingRulesDto(rr) .... ).ToSometing();
But I'm a little wary about that RoutingRulesDto(rr) constructor parameter.
If you use the fluent API for LINQ, you can conditionally add Where clauses.
var query = _content.RoutingRules.Where(r => r.BrandId == filter.BrandId);
if (filter.OriginZoneId != null) {
query = query.Where(r => r.OriginZoneId == filter.OriginZoneId);
}
if (filter.EshopServiceType != null) {
query = query.Where(r => r.EshopServiceType == filter.EshopServiceType);
}
// etc...
var result = query.ToArray();
Just to have my final solution in black and white, here's what I had in the end:
[HttpPost("filtered")]
public IActionResult GetFilteredRoutingRules([FromBody] RoutingSearchFilterDto filter)
{
// Query to be build on the routing rules table.
IQueryable<RoutingRules> query = _context.RoutingRules;
// Populate the linked foreign key entities.
query.Include(x => x.Hub).Include(y => y.DestinationZone).Include(z => z.OriginZone);
// Build dynamic where statements.
if (filter.BrandId != null)
query = query.Where(r => r.BrandId == filter.BrandId);
if (filter.OriginZoneId != null)
query = query.Where(r => r.OriginZoneId == filter.OriginZoneId);
if (filter.DestinationZoneId != null)
query = query.Where(r => r.DestinationZoneId == filter.DestinationZoneId);
if (filter.IsRuleActive != null)
query = query.Where(r => r.IsRuleActive == filter.IsRuleActive);
if (filter.RuleRanking != null)
query = query.Where(r => r.RuleRanking == filter.RuleRanking);
// If you want to add paging:
query = query.Skip(filter.PageSize * filter.PageNumber).Take(filter.PageSize);
// Perform select on the table and map the results.
var result = query.Select(r => new RoutingRulesDto
{
RoutingRuleId = r.RoutingRuleId,
BrandId = r.BrandId,
LastMileCarrierCode = r.LastMileCarrierCode,
CashOnDelivery = r.CashOnDelivery,
CreationTime = r.CreationTime,
CurrencyCode = r.CurrencyCode,
CurrencyDescription = Enum.Parse(typeof(Enumerations.CurrencyCode), r.CurrencyCode),
DestinationZoneId = r.DestinationZoneId,
EddFromDay = r.EddFromDay,
EddToDay = r.EddToDay,
ServiceType = r.ServiceType,
ServiceTypeName = Enum.Parse(typeof(Enumerations.ServiceType), r.EshopServiceType),
IsPickUpAvailable = r.IsPickUpAvailable,
LastUpdateTime = r.LastUpdateTime,
LastUpdateUser = r.LastUpdateUser,
OriginZoneId = r.OriginZoneId,
RuleRanking = r.RuleRanking,
SignOnDelivery = r.SignOnDelivery,
TermsOfDelivery = r.TermsOfDelivery,
TermsOfDeliveryName = Enum.Parse(typeof(Enumerations.TermsOfDelivery), r.TermsOfDelivery),
ValueOfGoods = r.ValueOfGoods,
WeightLowerLimit = r.WeightLowerLimit,
WeightUpperLimit = r.WeightUpperLimit,
FirstMileCarrierCode = r.FirstMileCarrierCode,
HubId = r.HubId,
IsInsuranceAvailable = r.IsInsuranceAvailable,
IsRuleActive = r.IsRuleActive,
HubName = r.Hub.HubName,
DestinationZoneName = r.DestinationZone.ZoneName,
OriginZoneName = r.OriginZone.ZoneName,
});
// The SQL produced includes the joins and where clauses as well as only
// selecting the column names that are required in the flattened return object.
return Ok(result);
}
Thanks for the help guys!

Linq to SQL - Ignore search parameters that are null or zero

I have a search form where the user can enter one to many parameters (Data, Status, Type, ID, Summary, Description) and leave the rest blank.
Here's my Linq to SQL code for my basic search. Is there a way to check each parameter within the Linq for zero, null or empty string?
List<RequestStatusModel> objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
where r.CustomerID == 31
select (new RequestStatusModel
{
RequestID = r.RequestID,
RequestTitle = r.RequestTitle,
DateAdded = r.DateAdded.ToString(),
DateChanged = r.DateChanged.ToString(),
RequestStatusID = r.StatusID
});
Thank you!
If it doesn't have to be in your linq statement you could just do it with classic if statements.
List<RequestStatusModel> objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
where r.CustomerID == 31
select (new RequestStatusModel
{
//...
});
if(data != null) //Replace with additional checks, if neccessary
{
query = query.where(x=> ...);
}
if(status != null)
{
query = query.where(x => ...)
}
If you want to only filter if certain criteria is passed, you should do something like this
var objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
where r.CustomerID == 31
if (String.IsNullOrEmpty(r.RequestID))
objRequestStatus = objRequestStatus.Where(x => x.RequestID == r.RequestID);
if (String.IsNullOrEmpty(r.RequestTitle))
objRequestStatus = objRequestStatus.Where(x => x.RequestTitle == r.RequestTitle);
//you other filters here
This sets up the expression to what you want based on which requests are passed
If you want to avoid all those ifs, you could do
List<RequestStatusModel> objRequestStatus = new List<RequestStatusModel>();
var query = from r in SimCareDB.Requests
where (r.CustomerID == 31) &&
(!String.IsNullOrEmpty(id) ? r.RequestID == id : true) &&
(!String.IsNullOrEmpty(status) ? r.StatusID == status : true)
/* And so on */
select (new RequestStatusModel
{
RequestID = r.RequestID,
RequestTitle = r.RequestTitle,
DateAdded = r.DateAdded.ToString(),
DateChanged = r.DateChanged.ToString(),
RequestStatusID = r.StatusID
});

Insert new rows based on date in Entity framework

I have been handed over an application that uses entity framework. I'm not familiar with entity and I'm having an issue that I can't figure out. This application was made to migrate data from a database to a more relational database. After the initial migration, we have to run it again to insert additional rows that were not part of the original migration. (There is a 3 week gap). I know that I have to put a check in and I want to do this by one of the columns we uses named "DateChanged" but unfortunately I'm not sure how to do this in entity. This is my first effort and it just shows in red which is depressing. I have searched on the internet but have found no solutions.
if (!newData.tVehicleLogs.Any(v => v.DateChanged.Value.ToShortDateString("6/27/2014")))//I'm not sure how to check the DateChanged here.
{
newData.tVehicleLogs.Add(deal);
comment = new tVehicleComment
{
Comment = vehicle.Reason,
DealID = deal.DealID,
CurrentComment = false
};
newData.tVehicleComments.Add(comment);
newData.SaveChanges();
int cId = comment.CommentID;
deal.CommentID = cId;
}
}
So as you can see I'm trying to check the date with the if statement, but I can't get the syntax correct... after trying everything I know to try .. which isn't much at this point.
I basically need to check if the DateChanged is from 6/27/2014 to today's date. If it's before then, then it has already been migrated over and doesn't need migrated over again. Where it says comment, if the row is new, then it inserts the old comment into the new comments table, then updates the tVehicleLogs table with the commentID. I'm just stuck on the date checking part. Any help is greatly appreciated!!
EDIT: This is the entire code for inserting the into tVehicleLogs..
if (MigrateLogs)
{
List<VLog> vlog = oldData.VLogs.ToList();
foreach (VLog vehicle in vlog)
{
tBank bank;
tCustomer cust;
tFIManager manag;
tSalesPerson sales;
tMake make;
tModel model;
tDealership dealership;
tMakeDealership makedeal;
tVehicleComment comment;
tInternalLocation location;
string dealershipName = getProperDealershipName(vehicle.Dealership, newData);
bank = (newData.tBanks.Any(banks => banks.BankName == vehicle.BankName) ? newData.tBanks.Where(b => b.BankName == vehicle.BankName).FirstOrDefault() : newData.tBanks.Add(new tBank { BankName = vehicle.BankName }));
cust = (newData.tCustomers.Any(customer => customer.CustomerNumber == vehicle.CustNumber) ? newData.tCustomers.Where(customer => customer.CustomerNumber == vehicle.CustNumber).FirstOrDefault() : newData.tCustomers.Add(new tCustomer { CustomerNumber = vehicle.CustNumber, CustomerName = vehicle.Buyer }));
//cust = (newData.tCustomers.Any(customer => customer.CustomerNumber == vehicle.CustNumber && customer.CustomerName == vehicle.CustNumber) ? newData.tCustomers.Where(customer => customer.CustomerNumber == vehicle.CustNumber).FirstOrDefault() : newData.tCustomers.Add(new tCustomer { CustomerNumber = vehicle.CustNumber, CustomerName = vehicle.Buyer }));
manag = (newData.tFIManagers.Any(manager => manager.FIName == vehicle.FIName) ? newData.tFIManagers.Where(manager => manager.FIName == vehicle.FIName).FirstOrDefault() : newData.tFIManagers.Add(new tFIManager { FIName = vehicle.FIName }));
sales = (newData.tSalesPersons.Any(person => person.SalesPersonNumber == vehicle.SalesPerson) ? newData.tSalesPersons.Where(person => person.SalesPersonNumber == vehicle.SalesPerson).FirstOrDefault() : newData.tSalesPersons.Add(new tSalesPerson { SalesPersonNumber = vehicle.SalesPerson }));
make = (newData.tMakes.Any(m => m.Make == vehicle.Make) ? newData.tMakes.Where(m => m.Make == vehicle.Make).FirstOrDefault() : newData.tMakes.Add(new tMake { Make = vehicle.Make }));
model = (newData.tModels.Any(m => m.Model == vehicle.Model) ? newData.tModels.Where(m => m.Model == vehicle.Model).FirstOrDefault() : newData.tModels.Add(new tModel { Model = vehicle.Model, MakeID = make.MakeID }));
dealership = (newData.tDealerships.Any(d => d.DealershipName == dealershipName) ? newData.tDealerships.Where(d => d.DealershipName == dealershipName).FirstOrDefault() : newData.tDealerships.Add(new tDealership { DealershipName = dealershipName }));
makedeal = (newData.tMakeDealerships.Any(d => d.MakeID == make.MakeID && d.DealershipID == dealership.DealershipID) ? newData.tMakeDealerships.Where(d => d.MakeID == make.MakeID && d.DealershipID == dealership.DealershipID).FirstOrDefault() : newData.tMakeDealerships.Add(new tMakeDealership { DealershipID = dealership.DealershipID, MakeID = make.MakeID }));
location = (newData.tInternalLocations.Any(l => l.LocationName == vehicle.Location) ? newData.tInternalLocations.Where(l => l.LocationName == vehicle.Location).FirstOrDefault() : newData.tInternalLocations.Add(new tInternalLocation { LocationName = vehicle.Location }));
//log = (newData.tVehicleLogs.Any(l => l.DealNumber == vehicle.FIMAST &&) ? newData.tVehicleLogs.Where(l => l.DealNumber == vehicle.FIMAST).FirstOrDefault() : newData.tVehicleLogs.Add(new tVehicleLog {DealNumber = vehicle.FIMAST }));
Int32 stat;
int? status;
if (Int32.TryParse(vehicle.Status, out stat))
status = stat;
else
status = null;
DateTime titled, bounced, dateReceived;
bool trueTitled = DateTime.TryParse(vehicle.Titled, out titled);
bool trueBounced = DateTime.TryParse(vehicle.Bounced, out bounced);
bool trueReceived = DateTime.TryParse(vehicle.DateReceived, out dateReceived);
int dealid = newData.tVehicleDeals.Where(v => v.DealNumber == vehicle.FIMAST).FirstOrDefault().DealID;
tVehicleLog deal = new tVehicleLog
{
DealNumber = vehicle.FIMAST,
StockNumber = vehicle.StockNumber,
BankID = bank.BankID,
CustomerID = cust.CustomerID,
FIManagerID = manag.FIManagerID,
SalesPersonID = sales.SalesPersonID,
VINNumber = null,
DealDate = vehicle.DealDate,
NewUsed = vehicle.NewUsed,
GrossProfit = vehicle.GrossProfit,
AmtFinanced = vehicle.AmtFinanced,
CloseDate = null,
Category = vehicle.RetailLease,
Status = status,
DealershipID = dealership.DealershipID,
NewDeal = false,
Archived = false,
InternalLocationID = location.InternalLocationID,
ChangedBy = vehicle.ChangedBy,
DateChanged = DateTime.Parse(vehicle.DateChanged),
Titled = null,
Bounced = null,
MakeID = make.MakeID,
ModelID = model.ModelID,
DealID = dealid,
CommentID = null
};
if (trueTitled)
deal.Titled = titled;
if (trueBounced)
deal.Bounced = bounced;
if (trueReceived)
deal.DateReceived = dateReceived;
DateTime targetDate = new DateTime(2014, 06, 27);
//if(!newData.tVehicleLogs.Any(v => v.DateChanged >= targetDate))
if(deal.DateChanged >= targetDate && !newData.tVehicleLogs.Any(v => v.DateChanged >= targetDate))
{
newData.tVehicleLogs.Add(deal);
comment = new tVehicleComment
{
Comment = vehicle.Reason,
DealID = deal.DealID,
CurrentComment = false
};
newData.tVehicleComments.Add(comment);
newData.SaveChanges();
int cId = comment.CommentID;
deal.CommentID = cId;
}
}
}
I don't think you need to use linq here (providing you've pulled the object down). Just check the dates.
// pull down the object
var deal = newData.tVehicleLogs.Where(v => v.Id == SOMEID).FirstOrDefault();
DateTime targetDate = new DateTime(2014,06,27);
if (tVehicleLogs.DateChaned <= DateTime.Now
&& tVehicleLogs.DateChaned >= targetDate) {
}
Alternatively, pull down all the objects that meet the date criteria and foreach over them.
List<YourObject> list = newData.tVehicleLogs.Where(v => v.DateChanged <= DateTime.Now
&& v.DateChanged >= targetDate).ToList();
foreach(var l in list) {
// do your stuff here
}

Categories

Resources