Best way to populate List<AnyObject> from database in C# - c#

I have 3 classes inherited from same class like
class S1:X{}
class S2:X{}
class S3:X{}
I need to write method to populate List<X> from Sql database. Currently, i am using SqlDataReader to populate. Each class has about 35 properties and db result also about 50K rows. Population is takes too long time. I am curious about the best way to populate large data into List. I am not able to use 3rd party packages because of corporation rules. Is there faster way than SqlDataReader?
Edit:
Modified code sample is below to describe what i am trying. Firstly, may be i should explain some points. SmartSqlReader is inherited from SqlDataReader, AutoMap method is mapper used Reflection.
using(SmartSqlReader reader = db.ExecuteReader(sp)) {
while (reader.Read()) {
bool isFlag1 = reader.GetBool("XX_TO_SEND");
bool isFlag2 = reader.GetBool("YY_TO_SEND");
bool isFlag3 = reader.GetBool("ZZ_TO_SEND");
if (!isFlag1 && !isFlag2 && !isFlag3) {
continue;
}
X x = new X() {
RecordId = reader.GetInt64("RECORD_ID"),
PropCxxx = reader.GetInt64("CXXX"),
PropCxxt = reader.GetInt32("CXXT"),
PropCxxsn = reader.GetString("CXXSN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXSN"),
PropCxxn = RemoveDiacritics(reader.GetString("CXXSN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXN").ToLower()),
PropCxxmn = reader.GetString("CXXSN2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXSN2"),
PropCxxs = reader.GetString("CXXS").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXS"),
Language = reader.GetString("LANGUAGE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("LANGUAGE"),
PropSxxx = reader.GetString("SXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("SXXX"),
MobilePhone1 = reader.GetString("MobilePhone1").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("MobilePhone1"),
MobilePhone2 = reader.GetString("MobilePhone2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("MobilePhone2"),
Email1 = reader.GetString("EMAIL1").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("EMAIL1"),
Email2 = reader.GetString("EMAIL2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("EMAIL2"),
Profile = reader.GetString("PROFILE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PROFILE"),
IsPersonnel = reader.GetString("PROFILE") == "XX" ? true : false,
IsPrivateBn = reader.GetString("IsOB").IsNullOrEmptyOrFullSpace() ? false : reader.GetBool("IsOB"),
VIP = reader.GetInt32("VIP_FLAG"),
Gender = reader.GetString("GENDER").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("GENDER"),
BusinessLine = reader.GetString("BUSINESSLINE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BUSINESSLINE"),
WorkPhone = reader.GetString("WORK_PHONE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("WORK_PHONE"),
HomePhone = reader.GetString("HOME_PHONE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("HOME_PHONE"),
CompanyName = reader.GetString("COMPANY_NAME").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("COMPANY_NAME"),
BranchName = reader.GetString("BRANCH_NAME").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BRANCH_NAME"),
PfNxxx = reader.GetString("PFNXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PFNXXX"),
Rgxxx = reader.GetString("RGXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("RGXXX"),
PCBN = reader.GetString("PCBN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PCBN"),
BPH = reader.GetString("BPH").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BPH"),
TranValue = reader.GetString("TRAN_VALUE"),
TranReferenceId = reader.GetString("TRAN_REFERENCE_ID"),
TranReferenceDate = reader.GetDateTime("TRAN_REFERENCE_DATE"),
Amount = reader.GetDecimal("AMOUNT"),
...
DynamicFields = new DynamicFields {
PropCxxx = reader.GetInt64("CXXX"),
FIELD1 = reader.GetString("DYNAMIC_FIELD1"),
FIELD2 = reader.GetString("DYNAMIC_FIELD2"),
FIELD3 = reader.GetString("DYNAMIC_FIELD3"),
FIELD4 = reader.GetString("DYNAMIC_FIELD4"),
FIELD5 = reader.GetString("DYNAMIC_FIELD5"),
FIELD6 = reader.GetString("DYNAMIC_FIELD6"),
FIELD7 = reader.GetString("DYNAMIC_FIELD7"),
FIELD8 = reader.GetString("DYNAMIC_FIELD8"),
FIELD9 = reader.GetString("DYNAMIC_FIELD9"),
FIELD10 = reader.GetString("DYNAMIC_FIELD10"),
FIELD11 = reader.GetString("DYNAMIC_FIELD11"),
FIELD12 = reader.GetString("DYNAMIC_FIELD12"),
FIELD13 = reader.GetString("DYNAMIC_FIELD13"),
FIELD14 = reader.GetString("DYNAMIC_FIELD14"),
FIELD15 = reader.GetString("DYNAMIC_FIELD15")
},
CampaignCodeOrLink = reader.GetString("CAMPAIGN_CODE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CAMPAIGN_CODE"),
ListId = reader.GetInt64("LIST_ID")
};
x.ChannelType = isFlag1 ? Enums.Channel.C1 : isFlag2 ? Enums.Channel.C2 : Enums.Channel.C3;
if (x.ChannelType == Enums.Channel.C1) {
S1 s1 = CommonUtils.AutoMap <S1> (x);
s1.S1Prop = reader.GetString("S1Prop");
xList.Add(s1);
}
else if (x.ChannelType == Enums.Channel.C2) {
S1 s2 = CommonUtils.AutoMap <S2> (x);
s2.S2Prop = reader.GetString("S2Prop");
xList.Add(s2);
} else {
S3 s3 = CommonUtils.AutoMap <S3> (x);
s3.S3Prop = reader.GetString("S3Prop");
xList.Add(s3);
}
}
}
Second Edition:
I just changed object initialization from X x = new X(){...} to
X x;
if(isFlag1)
{
x=new S1();
}
and so on. After that, 80K rows took approximately 10s. It's amazing. In conclusion, when i used CommonUtils.AutoMap method process took ~60m also when i used the second method it decreased to ~10s. This surprised me a lot.

I just changed object initialization method, so i removed CommonUtils.AutoMap that map objects use reflection. After all, 80K rows processed in ~10s instead of ~60m. Here is final code.
using(SmartSqlReader reader = db.ExecuteReader(sp)) {
while (reader.Read()) {
bool isFlag1 = reader.GetBool("XX_TO_SEND");
bool isFlag2 = reader.GetBool("YY_TO_SEND");
bool isFlag3 = reader.GetBool("ZZ_TO_SEND");
if (!isFlag1 && !isFlag2 && !isFlag3) {
continue;
}
X x;
if (isFlag1) {
var s = new S1();
s.S1Prop = reader.GetString("S1Prop");
x = s;
} else if (isFlag2) {
var s = new S2();
s.S2Prop = reader.GetString("S2Prop");
x = s;
} else {
var s = new S3();
s.S3Prop = reader.GetString("S3Prop");
x = s;
}
x.RecordId = reader.GetInt64("RECORD_ID"),
x.PropCxxx = reader.GetInt64("CXXX"),
x.PropCxxt = reader.GetInt32("CXXT"),
...
x.DynamicFields = new DynamicFields {
FIELD1 = reader.GetString("DYNAMIC_FIELD1"),
FIELD2 = reader.GetString("DYNAMIC_FIELD2"),
FIELD3 = reader.GetString("DYNAMIC_FIELD3"),
FIELD4 = reader.GetString("DYNAMIC_FIELD4"),
FIELD5 = reader.GetString("DYNAMIC_FIELD5"),
FIELD6 = reader.GetString("DYNAMIC_FIELD6"),
FIELD7 = reader.GetString("DYNAMIC_FIELD7"),
FIELD8 = reader.GetString("DYNAMIC_FIELD8"),
FIELD9 = reader.GetString("DYNAMIC_FIELD9"),
FIELD10 = reader.GetString("DYNAMIC_FIELD10"),
FIELD11 = reader.GetString("DYNAMIC_FIELD11"),
FIELD12 = reader.GetString("DYNAMIC_FIELD12"),
FIELD13 = reader.GetString("DYNAMIC_FIELD13"),
FIELD14 = reader.GetString("DYNAMIC_FIELD14"),
FIELD15 = reader.GetString("DYNAMIC_FIELD15")
},
};
xList.Add(x);
}
}

Related

Kendo Grid json string exceeds the value set on the maxJsonLength property

I keep receiving this error when trying to get a json string into my kendo grid. I have set the max size in the web.config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644">
</jsonSerialization>
</webServices>
</scripting>
I've also tried adding it directly to the controller. This is how I generate my json string
public ActionResult ChangeRequests_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(GetRequests().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public static IEnumerable<ChangeRequestsVM> GetRequests()
{
var model = CompanyContextFactory.GetContextPerRequest();
var chrwVM = model.ChangeRequestsHDRs.Where(ch=> ch.CompanyID == GlobalVariables.CompanyID).Select(ch=> new ChangeRequestsVM
{
RequestID = ch.RequestID,
CompanyID = ch.CompanyID,
ClientID = ch.ClientID,
EmployeeID = (string.IsNullOrEmpty(ch.EmployeeID)) ? "NA" : ch.EmployeeID,
AssignmentType = ch.AssignmentType,
Key1 = ch.Key1,
Key2 = ch.Key2,
LogonID = ch.LogonID,
ProcessDate = ch.ProcessDate,
ProcessTime = ch.ProcessTime,
ProcessUserID = ch.ProcessUserID,
RequestDate = ch.RequestDate,
RequestExport = ch.RequestExport,
RequestNote = ch.RequestNote,
RequestOrigin = Convert.ToChar(ch.RequestOrigin),
RequestProcess = ch.RequestProcess,
RequestStatus = ch.RequestStatus,
RequestTime = ch.RequestTime,
RequestType = Convert.ToChar(ch.RequestType),
ResponseNote = ch.ResponseNote,
TableName = ch.TableName,
TransferDate = ch.TransferDate,
TransferTime = ch.TransferTime,
TransferUserID = ch.TransferUserID,
dispOrigin = (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.System) ? "System" : (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.Client) ? "Client" : "Employee",
dispRequestType = (Convert.ToChar(ch.RequestType) == ChangeRequestType.Insert) ? "Insert" : (Convert.ToChar(ch.RequestType) == ChangeRequestType.Alter) ? "Change" : "Delete",
dispStatus = FieldTranslation.GetEnumDescription(typeof(enChangeRequestStatus), ch.RequestStatus ?? 0)
}).OrderByDescending(ch=> ch.RequestID);
return chrwVM;
}
This is the full error I'm getting. The string being sent is HUGE but I am not sure how to figure out how big it is. What am I missing to get this JSON string to return without the error?
Error during serialization or deserialization using the JSON JavaScriptSerializer.
The length of the string exceeds the value set on the maxJsonLength property
I've also tried it this way
public ActionResult ChangeRequests_Read([DataSourceRequest] DataSourceRequest request)
{
var result = Json(GetRequests().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
var serializer = new JavaScriptSerializer();
// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;
var resultData = new { result };
var result1 = new ContentResult
{
Content = serializer.Serialize(resultData),
ContentType = "application/json"
};
return result1;
}
public static IEnumerable<ChangeRequestsVM> GetRequests()
{
var model = CompanyContextFactory.GetContextPerRequest();
var chrwVM = model.ChangeRequestsHDRs.Where(ch=> ch.CompanyID == GlobalVariables.CompanyID).Select(ch=> new ChangeRequestsVM
{
RequestID = ch.RequestID,
CompanyID = ch.CompanyID,
ClientID = ch.ClientID,
EmployeeID = (string.IsNullOrEmpty(ch.EmployeeID)) ? "NA" : ch.EmployeeID,
AssignmentType = ch.AssignmentType,
Key1 = ch.Key1,
Key2 = ch.Key2,
LogonID = ch.LogonID,
ProcessDate = ch.ProcessDate,
ProcessTime = ch.ProcessTime,
ProcessUserID = ch.ProcessUserID,
RequestDate = ch.RequestDate,
RequestExport = ch.RequestExport,
RequestNote = ch.RequestNote,
RequestOrigin = Convert.ToChar(ch.RequestOrigin),
RequestProcess = ch.RequestProcess,
RequestStatus = ch.RequestStatus,
RequestTime = ch.RequestTime,
RequestType = Convert.ToChar(ch.RequestType),
ResponseNote = ch.ResponseNote,
TableName = ch.TableName,
TransferDate = ch.TransferDate,
TransferTime = ch.TransferTime,
TransferUserID = ch.TransferUserID,
dispOrigin = (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.System) ? "System" : (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.Client) ? "Client" : "Employee",
dispRequestType = (Convert.ToChar(ch.RequestType) == ChangeRequestType.Insert) ? "Insert" : (Convert.ToChar(ch.RequestType) == ChangeRequestType.Alter) ? "Change" : "Delete",
dispStatus = FieldTranslation.GetEnumDescription(typeof(enChangeRequestStatus), ch.RequestStatus ?? 0)
}).OrderByDescending(ch=> ch.RequestID);
return chrwVM;
}

C# scoring based on answers

I have some data that has values in properties called Poll_1, Poll_2, Poll_3, ...Poll_8.
I need to get a score based on this criteria:
For each Poll_1 thru Poll_4 that is not empty, FirstPollCount is incremented.
For each Poll_5 thru Poll_8 that is not empty, SecondPollCount is incremented.
This is currently how I'm doing it.
int pass1 = 0;
int pass2 = 0;
if (rec.Poll_1.Trim() != "") { pass1++; };
if (rec.Poll_2.Trim() != "") { pass1++; };
if (rec.Poll_3.Trim() != "") { pass1++; };
if (rec.Poll_4.Trim() != "") { pass1++; };
if (rec.Poll_5.Trim() != "") { pass2++; };
if (rec.Poll_6.Trim() != "") { pass2++; };
if (rec.Poll_7.Trim() != "") { pass2++; };
if (rec.Poll_8.Trim() != "") { pass2++; };
aa.FirstPollCount = pass1;
aa.SecondPollCount = pass2;
Is there an easier way to do this?
Not really any better, but if you want to look to an alternative
List<string> firstPolls = new List<string>()
{
rec.Poll_1.Trim(), rec.Poll_2.Trim(),rec.Poll_3.Trim(),rec.Poll_4.Trim()
};
int pass1 = firstPolls.Count(x => x != "");
List<string> secondPolls = new List<string>()
{
rec.Poll_5.Trim(), rec.Poll_6.Trim(),rec.Poll_7.Trim(),rec.Poll_8.Trim()
};
int pass2= secondPolls.Count(x => x != "");
By the way, what is the class for the rec variable? Probably an improvement is to add a internal method that executes this code and returns the value:
int pass1 = rec.GetFirstScoreCount();
int pass2 = rec.GetSecondScoreCount();
thus hiding the implementation details (the Trim() != "") from the client code that uses the rec variable.
You can use Linq:
string s1 = "Random String";
string s2 = "Random String";
string s3 = "Random String";
string s4 = "Random String";
string s5 = "Random String";
string s6 = "";
string s7 = "Random String";
string s8 = "Random String";
int countPool1 = (new List<string>(){s1, s2, s3, s4}).Count(t => t.Trim() != "");
int countPool2 = (new List<string>() { s5, s6, s7, s8 }).Count(t => t.Trim() != "");
Console.Out.WriteLine("Pool 1 : " + countPool1);
Console.Out.WriteLine("Pool 2 : " + countPool2);
With output:
Pool 1 : 4
Pool 2 : 3
You can also use Linq Query Syntax:
List<string> pol1to4Coll = new List<string>() { rec.Poll_1, rec.Poll_2, rec.Poll_3, rec.Poll_4 };
List<string> pol5to8Coll = new List<string>() { rec.Poll_5, rec.Poll_6, rec.Poll_7, rec.Poll_8 };
int countPol1to4Coll = (from poll in pol1to4Coll
where poll != ""
select poll).Count();
int countPol5to8Coll = (from poll in pol5to8Coll
where poll != ""
select poll).Count();

How to correctly refactor this big and with very similar code if/else statements?

I'm trying to refactor this code that would be much more bigger and I'm wondering which is the better way to do it.
string obje = String.Empty;
long userId = 0;
long objNewId = 0;
long objOldId = 0;
string action = String.Empty;
if (oldObject.GetType() == typeof(FooDto))
{
obje = ConstantParams.WCFLOG_APPLICATION_Foo;
FooDto newFoo = (FooDto)response.Data;
FooDto oldFoo = (FooDto)oldObject;
userId = newFoo.UserApplicationId;
objNewId = newFoo.Id;
objOldId = oldFoo.Id;
}
else if (oldObject.GetType() == typeof(BarDto))
{
obje = ConstantParams.WCFLOG_APPLICATION_Bar;
BarDto newBar = (BarDto)response.Data;
BarDto oldBar = (BarDto)oldObject;
userId = newBar.UserApplicationId;
objNewId = newBar.Id;
objOldId = oldBar.Id;
}
action = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;
string message = Helper.GenerateMessage(action, obje, userId, objNewId);
The thing is that it may be possible to write something like this but I don't know if something like that is possible:
obje = ConstantParams.WCFLOG_APPLICATION_[[XXX]];
[[XXX]]Dto newItem = ([[XXX]]Dto)response.Data;
[[XXX]]Dto oldItem = ([[XXX]]Dto)oldObject;
userId = newItem .UserApplicationId;
objNewId = newItem .Id;
objOldId = oldItem .Id;
Assuming Foo, Bar, and their counterparts all inherit from or implement a common class which holds Id and UserApplicationId - let's call it SuperclassDto because you don't specify, this can be as simple as:
string obje = String.Empty;
long userId = 0;
long objNewId = 0;
long objOldId = 0;
string action = String.Empty;
obje = ConstantParams.WCFLOG_APPLICATION_Foo;
SuperclassDto newDto = (SuperclassDto)response.Data;
SuperclassDto oldDto = (SuperclassDto)oldObject;
userId = newFoo.UserApplicationId;
objNewId = newDto.Id;
objOldId = oldDto.Id;
action = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;
string message = Helper.GenerateMessage(action, obje, userId, objNewId);
If your inheritance/implementation hierarchy isn't this simple, you should be able to coerce into such a state.

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
}

LINQ2SQL: Using the parent ID in a child object twice - parent ID equals zero

I've got the following code and I wish to set the AssignmentID and the ToDoAssignmentID to the same value. Setting AssignmentID to workOrder.AssignmentID works just fine, but setting ToDoAssignmentID to workOrder.AssignmentID results in ToDoAssignmentID being set to 0. Why is that?
workOrder.ClientID = this.Client.ClientID;
workOrder.AssignmentID = this.WorkOrderID;
workOrder.AssignmentNumber = this.GetNextWorkOrderNumber(this.Client);
workOrder.CustomerID = this._CustomerID;
workOrder.DateCreated = this.Created;
workOrder.DatoAvtaltStart = this.AgreedStart == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedStart;
workOrder.DatoAvtaltSlutt = this.AgreedEnd == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedEnd;
workOrder.DateStopped = this.Ended == DateTime.MinValue ? new DateTime().MinSDTValue() : this.Ended;
workOrder.CreatedByEmployeeID = this._CreatedByEmployeeID;
workOrder.ResponsibleEmployeeID = this._ResponsibleEmployeeID;
workOrder.KoordinatorAnsattId = this._CoordinatorEmployeeID;
workOrder.Description = this.Description;
workOrder.Notes = this.Notes;
workOrder.EstimertTimerFra = this.EstimatedHoursFrom;
workOrder.EstimertTimerTil = this.EstimatedHoursTo;
workOrder.EstimatedBillingDate = this.EstimatedBillingDate;
workOrder.Priority = (byte)this.Priority;
workOrder.OBS = this.OBS;
workOrder.CustomerReference = this.CustomersReference;
workOrder.InterntOrdrenr = this.InternalOrderNumber;
workOrder.EksterntOrdrenr = this.ExternalOrderNumber;
workOrder.AssignmentStatusID = this.WorkOrderStatusID;
foreach (var activity in this.Activities)
{
var ProductID = 0;
try
{
ProductID = activity.Product.ProductID;
}
catch (Exception ex)
{
}
workOrder.Activities.Add(new Activity()
{
ActivityID = activity.ActivityID,
ClientID = activity.Client.ClientID,
AssignmentID = workOrder.AssignmentID,
Description = activity.Description,
Notes = activity.Notes,
IsBillable = activity.Billable,
Priority = (byte)activity.Priority,
ActivityTypeID = activity.ActivityType.TypeID,
PerformedByEmployeeID = activity.PerformedByEmployee.EmployeeID,
ProductID = ProductID,
ToDo = activity.IsPlanned,
ToDoAssignmentID = workOrder.AssignmentID,
ToDoCustomerID = workOrder.CustomerID
});
}
workOrderContext.SubmitChanges();
The key is not to think database style, but ORM style.
So instead of setting keys, you assign entities.
so change
ToDoAssignmentID = workOrder.AssignmentID
to (most probable guess of tablenames, check the definition of your entity) the following assignment of entities
ToDoAssignment = workOrder
This will be handled during SubmitChanges as well.

Categories

Resources