C#, Linq2Sql, .NET 2.0, SQL 2005 Express
When I run the following code I get a
InvalidCastException unable to cast of type System.Byte[] to System.String
This does not occur on all rows in the table i.e. this code runs fine soemtimes.
I checked there are no columns in the table that linq declares as SYstem.Byte[]
The stack trace says the exception occurs on the linq statement and when I F11
into the code the GetProject is never called the exception occurs before this method
is called.
So I think it is Linq framework bug.
This has got me stumped? any ideas?
[code]
public Project GetProject(int id)
{
var project = (from row in _dbctx.Projects
where row.ProjectID == id
select row).SingleOrDefault();
Project proj = GetProject(project);
return proj;
}
private Project GetProject(TBRServices.Domain.TBR.DataContext.Project sqlproject)
{
Project project = new Project();
project.ProjectID = sqlproject.ProjectID;
project.ProjectName = sqlproject.ProjectName;
project.ProjectDescription = sqlproject.ProjectDescription;
project.ClientID = sqlproject.ClientID;
project.PurchaseOrderNumber = sqlproject.PurchaseOrderNumber;
project.ProjectTotalBillingEstimate = sqlproject.ProjectTotalBillingEstimate;
project.EmployeeID = sqlproject.EmployeeID;
project.ProjectBeginDate = sqlproject.ProjectBeginDate.ToString();
project.ProjectEndDate = sqlproject.ProjectEndDate.ToString();
project.Active = sqlproject.Active;
project.InclGST = sqlproject.InclGST;
project.ContractRate = sqlproject.ContractRate;
project.MarginRate = sqlproject.MarginRate;
project.Notes = sqlproject.Notes;
project.PayrollTax = sqlproject.PayrollTax;
project.EmployeeReference = sqlproject.EmployeeReference;
project.PayReference = sqlproject.PayReference;
project.ProjectLocation = sqlproject.ProjectLocation;
project.ContractTypeID = sqlproject.ContractTypeID;
project.DoNotCalcMarginOrGST = sqlproject.DoNotCalcMarginOrGST;
project.ConvertToInvoice = sqlproject.ConvertToInvoice;
project.AuthFirstname = sqlproject.AuthFirstname;
project.AuthLastname = sqlproject.AuthLastname;
project.AuthEmail = sqlproject.AuthEmail;
project.CapturedDocumentType = sqlproject.CapturedDocumentType;
project.TimesheetProcessingType = sqlproject.TimesheetProcessingType;
project.TimesheetFrequency = sqlproject.TimesheetFrequency;
project.AggregateTimesheet = sqlproject.AggregateTimesheet;
project.AggregateAutomatically = sqlproject.AggregateAutomatically;
project.BusProcEmpCut = sqlproject.BusProcEmpCut;
project.BusProcAgencyCut = sqlproject.BusProcAgencyCut;
project.SendCopyTimesheet = sqlproject.SendCopyTimesheet;
project.TimesheetRecipient1 = sqlproject.TimesheetRecipient1;
project.TimesheetRecipient2 = sqlproject.TimesheetRecipient2;
project.SendCopyInvoice = sqlproject.SendCopyInvoice;
project.PublishedOn = sqlproject.PublishedOn.ToString();
project.SendAggTimesheetsWhenReceived = sqlproject.SendAggTimesheetsWhenReceived;
project.AuthoriseInvoice = sqlproject.AuthoriseInvoice;
project.HourlyDailyMthly = sqlproject.HourlyDailyMthly;
project.EmployeeCategory = sqlproject.EmployeeCategory;
project.AgencyRate = sqlproject.AgencyRate;
project.ConsultantID = sqlproject.ConsultantID;
project.SendCopyInvoiceEmployee = sqlproject.SendCopyInvoiceEmployee;
project.UseClientDetailsForTimesheet = sqlproject.UseClientDetailsForTimesheet;
project.FaxedTimesheet = sqlproject.FaxedTimesheet;
project.TimesheetEditable = sqlproject.TimesheetEditable;
project.IncludeInReport = sqlproject.IncludeInReport;
project.SendLogonEmail = sqlproject.SendLogonEmail;
project.NoticePeriodID = sqlproject.NoticePeriodID;
project.ManagerCanViewPaidUnpaid = sqlproject.ManagerCanViewPaidUnpaid;
project.LesterSalesStaff = sqlproject.LesterSalesStaff;
project.IncludeSalesReport = sqlproject.IncludeSalesReport;
project.CurrencyAccount = sqlproject.CurrencyAccount;
project.LeaveMustBeAuthorisedTimesheet = sqlproject.LeaveMustBeAuthorisedTimesheet;
project.LeaveMustBeAuthorisedLeaveForm = sqlproject.LeaveMustBeAuthorisedLeaveForm;
project.DefaultHoursWorkedWeek = sqlproject.DefaultHoursWorkedWeek;
project.DefaultHoursWorkedDay = sqlproject.DefaultHoursWorkedDay;
project.AccruedLeaveStartDate = sqlproject.AccruedLeaveStartDate.ToString();
project.AllowLeaveMoreThanAccrued = sqlproject.AllowLeaveMoreThanAccrued;
project.IsPaidASalary = sqlproject.IsPaidASalary;
project.AgencyID = sqlproject.AgencyID;
project.SendEmailToManagerToOKLeave = sqlproject.SendEmailToManagerToOKLeave;
project.SpecialPayrollNotes = sqlproject.SpecialPayrollNotes;
project.SpecialInvoicingNotes = sqlproject.SpecialInvoicingNotes;
project.InvoiceTermsMessage = sqlproject.InvoiceTermsMessage;
project.AuthManagerPhone = sqlproject.AuthManagerPhone;
project.LMF = sqlproject.LMF;
project.LMFPercent = sqlproject.LMFPercent;
project.LMFInclInPayRate = sqlproject.LMFInclInPayRate;
project.LMFOnTop = sqlproject.LMFOnTop;
project.AgencyComm = sqlproject.AgencyComm;
project.AgencyCommPercent = sqlproject.AgencyCommPercent;
project.AgencyCommInclInPayRate = sqlproject.AgencyCommInclInPayRate;
project.AgencyCommOnTop = sqlproject.AgencyCommOnTop;
project.PayRateInclMargin = sqlproject.PayRateInclMargin;
project.MarginRatePercent = sqlproject.MarginRatePercent;
project.MarginRateGST = sqlproject.MarginRateGST;
project.MarginRateInclInPayRate = sqlproject.MarginRateInclInPayRate;
project.MarginRateOnTop = sqlproject.MarginRateOnTop;
project.PayRateInclSuper = sqlproject.PayRateInclSuper;
project.PayrollTaxAmount = sqlproject.PayrollTaxAmount;
project.PayrollTaxPercent = sqlproject.PayrollTaxPercent;
project.PayrollTaxInclInPayRate = sqlproject.PayrollTaxInclInPayRate;
project.PayrollTaxOnTop = sqlproject.PayrollTaxOnTop;
project.TypeOfArrangement = sqlproject.TypeOfArrangement;
project.ParameterRequired = sqlproject.ParameterRequired;
project.SpecialPayrollEnabled = sqlproject.SpecialPayrollEnabled;
project.ClientContactUsedReceiptOfInvoiceID = sqlproject.ClientContactUsedReceiptOfInvoiceID;
project.ExcludeEmpNameOnInvoice = sqlproject.ExcludeEmpNameOnInvoice;
project.BPForReporting = sqlproject.BPForReporting;
project.UseGemteqInvoiceFormat = sqlproject.UseGemteqInvoiceFormat;
project.TreatPayrollDetailsSameAsBP = sqlproject.TreatPayrollDetailsSameAsBP;
return project;
}
[/code]
Check the answer to a similar SO question. It will not be the exact answer but may help you find the problem in your query -
Problem with Linq to SQL
unable to cast of type System.Byte[] to System.String
Indicates that a property in sqlproject is stored as byte[] while the corresponding property in project is a string
Related
I have the LINQ query with the simple select statement which maps the columns from a table to the custom entity.
I have quite a few fields so I'm trying to select one by one and leave one field out. This way seems pretty silly to me. There was an option such as not select in SQL, it should have a counterpart in the entity framework.
I don't want to select the image area in this query. Do I have to write such a long code for this?
var result = from ch in _tenantDbContext.CariHesap
where ch.KartTipi == cariHesapKartTip
select new CariHesap
{
Id = ch.Id,
HesapKodu = ch.HesapKodu,
Unvan = ch.Unvan,
Ad = ch.Ad,
Soyad = ch.Soyad,
AktifPasif = ch.AktifPasif,
KartTipi = ch.KartTipi,
IslemTipi = ch.IslemTipi,
BakGostSekli = ch.BakGostSekli,
DvzTL = ch.DvzTL,
DovizCinsi = ch.DovizCinsi,
KrediLimiti = ch.KrediLimiti,
DvzKrediLimiti = ch.DvzKrediLimiti,
BolgeKod = ch.BolgeKod,
OzelKod = ch.OzelKod,
GrupKod = ch.GrupKod,
TipKod = ch.TipKod,
MhsKod = ch.MhsKod,
MasrafMerkezi = ch.MasrafMerkezi,
VergiDairesi = ch.VergiDairesi,
HesapNo = ch.HesapNo,
FaturaChk = ch.FaturaChk,
IskontoOran = ch.IskontoOran,
OpsiyonGunu = ch.OpsiyonGunu,
OdemeGunu = ch.OdemeGunu,
OdemePlani = ch.OdemePlani,
KulSatisFiyat = ch.KulSatisFiyat,
CHKodu = ch.CHKodu,
KDVTevfikatUygula = ch.KDVTevfikatUygula,
KDVMuaf = ch.KDVMuaf,
KDVMuafAck = ch.KDVMuafAck,
FormBaBsUnvan = ch.FormBaBsUnvan,
SirketEMail = ch.SirketEMail,
SirketWebAdres = ch.SirketWebAdres,
SatIslemEMail = ch.SatIslemEMail,
SatAlmaIslemEMail = ch.SatAlmaIslemEMail,
FinIslemEMail = ch.FinIslemEMail,
UnvanFaturadan = ch.UnvanFaturadan,
EFatSenaryo = ch.EFatSenaryo,
EIrsSenaryo = ch.EIrsSenaryo,
EMMSenaryo = ch.EMMSenaryo,
EFatEtiket = ch.EFatEtiket,
EIrsEtiket = ch.EIrsEtiket,
MusBrmSubeTanim = ch.MusBrmSubeTanim,
MusBrmSubeDeger = ch.MusBrmSubeDeger,
MusCHKoduTanim = ch.MusCHKoduTanim,
MusCHKoduDeger = ch.MusCHKoduDeger,
LegalEntityID = ch.LegalEntityID,
LegalEntityName = ch.LegalEntityName,
EArsivTeslimSekli = ch.EArsivTeslimSekli,
EArsivTeslimEMail1 = ch.EArsivTeslimEMail1,
EArsivTeslimEMail2 = ch.EArsivTeslimEMail2,
EArsivTeslimEMail3 = ch.EArsivTeslimEMail3,
FaturaXSLT = ch.FaturaXSLT,
IrsaliyeXSLT = ch.IrsaliyeXSLT,
SGKChk = ch.SGKChk,
SGKFaturaTipi = ch.SGKFaturaTipi,
KamuChk = ch.KamuChk,
Kod1 = ch.Kod1,
Kod2 = ch.Kod2,
Kod3 = ch.Kod3,
Kod4 = ch.Kod4,
Kod5 = ch.Kod5,
Kod6 = ch.Kod6,
Kod7 = ch.Kod7,
Kod8 = ch.Kod8,
Kod9 = ch.Kod9,
Kod10 = ch.Kod10,
Kod11 = ch.Kod11,
Kod12 = ch.Kod12,
Kod13 = ch.Kod13,
Kod14 = ch.Kod14,
Kod15 = ch.Kod15,
Nesne1 = ch.Nesne1,
Nesne2 = ch.Nesne2,
};
I am consuming trade and quote data with BLPAPI in C#. When I process a LAST_TRADE_PRICE_TIME_TODAY_RT like this using //blp/mktdata service and processing the SUBCRIPTION_DATA event fine except for this message element:
{MarketDataEvents = {
RT_TIME_OF_TRADE = 2022-06-23
INDICATIVE_NEAR =
IMBALANCE_BUY =
IMBALANCE_SELL =
ORDER_IMB_BUY_VOLUME =
ORDER_IMB_SELL_VOLUME =
THEO_PRICE =
IMBALANCE_INDIC_RT =
PREV_CLOSE_VALUE_REALTIME = 11737.5
TRADING_DT_REALTIME = 2022-06-24
PREV_TRADING_DT_REALTIME = 2022-06-23
PX_ASK_LME_OFFICIAL_RT =
NUM_TRADES_RT = 0
PX_OFFICIAL_AUCTION_RT =
LAST_UPDATE_BID_RT = 2022-06-23
LAST_UPDATE_ASK_RT = 2022-06-23
OFFICIAL_AUCTION_VOLUME_RT =
IN_AUCTION_RT =
TURNOVER_TODAY_REALTIME =
OFFICIAL_OPEN_AUCTION_PRICE_RT =
OFFICIAL_OPEN_AUCTION_VOLUME_RT =
OFFICIAL_CLOSE_AUCTION_PRICE_RT =
OFFICIAL_CLOSE_AUCTION_VOLUME_RT =
AUCTION_EXTENSION_RT =
BLOCK_TRADE_ACCUM_VOLUME_RT =
TOTAL_MSG_SCRAPED_OFFERS_RT =
EVENT_TIME = 22:30:00.000
VOLUME_THEO =
OPEN_YLD_TDY_RT =
HIGH_YLD_TDY_RT =
LOW_YLD_TDY_RT =
LAST_YLD_TDY =
MID_TDY =
SIZE_LAST_TRADE_TDY =
RT_PX_CHG_NET_1D = 171.75
RT_PX_CHG_PCT_1D = 1.485
OPEN_TDY =
ASK_SIZE_TDY =
BID_SIZE_TDY =
VOLUME_TDY =
LAST_PRICE_TDY =
BID_TDY =
ASK_TDY =
HIGH_TDY =
LOW_TDY =
BID_YLD_TDY =
ASK_YLD_TDY =
TIME = 2022-06-23
LAST_UPDATE_ALL_SESSIONS_RT =
PX_OPEN_ALL_WITH_SWITCHOVER_RT =
BID_ALL_SESSION_TDY_RT =
ASK_ALL_SESSION_TDY_RT =
CONTINUOUS_TRAD_CLOS_BID_PX_RT =
CONTINUOUS_TRAD_CLOS_ASK_PX_RT =
POST_CLOSING_AUCTION_BID_PX_RT =
POST_CLOSING_AUCTION_ASK_PX_RT =
LAST_TRADE_RECEIVED_TIME_RT =
PRICE_CHANGE_ON_DAY_RT = 171.75
PRICE_LAST_ASK_RT =
PRICE_LAST_BID_RT =
PRICE_HIGH_RT =
PRICE_LOW_RT =
PRICE_OPEN_RT =
LAST_TRADE_PRICE_TODAY_RT =
PREVIOUS_TOTAL_VOLUME_RT = 622197
PREVIOUS_CLOSE_ADJ_BY_GR_DVD_RT =
TIME_AUCTION_CALL_CONCLUSION_RT =
PER_TRADE_VWAP_REALTIME =
PER_TRADE_VWAP_TURNOVER_RT =
PER_TRADE_VWAP_VOLUME_RT =
OPEN_HIGH_PRICE_REALTIME =
OPEN_LOW_PRICE_REALTIME =
CLOSE_HIGH_PRICE_REALTIME =
CLOSE_LOW_PRICE_REALTIME =
EXCHANGE_FOR_PHYSICAL_VOLUME_RT =
EXCHANGE_FOR_SWAP_VOLUME_RT =
LAST_BID_TIME_TODAY_REALTIME =
LAST_ASK_TIME_TODAY_REALTIME =
LAST_MID_TIME_TODAY_REALTIME =
LAST_PRICE_TIME_TODAY_REALTIME =
LAST_TRADE_PRICE_TIME_TODAY_RT =
MINIMUM_ORDER_LIMIT_PRICE_RT =
MAXIMUM_ORDER_LIMIT_PRICE_RT =
MIN_DYNAMIC_TRADING_LIMIT_PX_RT =
MAX_DYNAMIC_TRADING_LIMIT_PX_RT =
15_SECOND_PRICE_CHANGE_RT =
1_MINUTE_PRICE_CHANGE_RT =
5_MINUTE_PRICE_CHANGE_RT =
15_MINUTE_PRICE_CHANGE_RT =
1_HOUR_PRICE_CHANGE_RT =
CIRCUIT_BREAKER_TRIG_SIGNAL_RT =
LAST_CONTINUOUS_TRADE_PRICE_RT =
DYNAMIC_TRADING_LIMITS_REF_PX_RT =
LAST_OFF_BOOK_TRADE_PRICE_RT =
CB_TRIGGER_SIGNAL_START_TIME_RT =
CB_TRIGGER_SIGNAL_END_TIME_RT =
EFFECTIVE_DATE_RT =
OPEN_TRADE_PRICE_TODAY_RT =
HIGH_TRADE_PRICE_TODAY_RT =
LOW_TRADE_PRICE_TODAY_RT =
EXCHANGE_FOR_RISK_VOLUME_RT =
BLOOMBERG_CLOSE_PRICE_TODAY_RT =
PRICE_CLOSE_CC_TODAY_RT =
SUB_SEC_TM_AUCT_CALL_CNCLSN_RT =
THEORETICAL_TIME_TODAY_RT =
ON_EXCHANGE_VOLUME_TODAY_RT =
ON_BOOK_VOLUME_TODAY_RT =
LIT_BOOK_VOLUME_TODAY_RT =
CONTINUOUS_VOLUME_TODAY_RT =
AUCTION_VOLUME_TODAY_RT =
SCHEDULED_AUCT_VOLUME_TODAY_RT =
OPENING_AUCTION_VOLUME_RT =
CLOSING_AUCTION_VOLUME_RT =
INTRADAY_AUCTION_VOLUME_TODAY_RT =
UNSCHEDULED_AUCT_VOLUME_TODAY_RT =
TRADE_LAST_CLOSE_VOLUME_TODAY_RT =
PRE_POST_AUTO_EXECTN_VOL_TDY_RT =
DARK_BOOK_VOLUME_TODAY_RT =
ON_BK_NEG_BTF_OR_CC_VOL_TDY_RT =
ODD_LOT_BOOK_VOLUME_TODAY_RT =
OFF_BOOK_VOLUME_TODAY_RT =
NEGOTIATED_VOLUME_TODAY_RT =
OFF_BK_BLOCK_OR_CC_VOLUME_TDY_RT =
OFF_BOOK_ODD_LOT_VOLUME_TODAY_RT =
OTC_VOLUME_TODAY_RT =
SYSTEMATIC_INTERNAL_VOL_TDY_RT =
REPORTED_DARK_VOLUME_TODAY_RT =
PERCENT_CHANGE_ON_DAY_TODAY_RT =
NET_CHANGE_ON_DAY_TODAY_RT =
LAST_TRADE_AM_SESSION_TODAY_RT =
OPEN_PRICE_AM_SESSION_TODAY_RT =
HIGH_PRICE_AM_SESSION_TODAY_RT =
LOW_PRICE_AM_SESSION_TODAY_RT =
VOLUME_AM_SESSION_TODAY_RT =
LAST_TRADE_PM_SESSION_TODAY_RT =
OPEN_PRICE_PM_SESSION_TODAY_RT =
HIGH_PRICE_PM_SESSION_TODAY_RT =
LOW_PRICE_PM_SESSION_TODAY_RT =
VOLUME_PM_SESSION_TODAY_RT =
EXCHANGE_VWAP_TODAY_RT =
SETTLEMENT_PRESENT_VALUE_RT =
MATURITY_CALIBRATION_RATE_RT =
MATURITY_CALIBRATION_PV_RT =
CONTRIBUTED_RECOVERY_RATE_RT =
PAR_SPREAD_BID_RT =
PAR_SPREAD_ASK_RT =
LIQUIDITY_INDICATOR_RT =
PRICE_BID_CLOSE_TODAY_RT =
PRICE_ASK_CLOSE_TODAY_RT =
OFFICIAL_CLOSE_TODAY_RT =
PREVIOUS_BLOOMBERG_CLOSE_PX_RT = 11737.5
PREVIOUS_LAST_TRADE_PRICE_RT = 11688
BLOOMBERG_SEND_TIME_RT = 2022-06-23T21:31:23.469+00:00
10_MINUTE_PRICE_CHANGE_RT =
30_MINUTE_PRICE_CHANGE_RT =
BLOOMBERG_CLOSE_PX_AM_TODAY_RT =
PERIODIC_AUCT_ON_DMD_VOL_TDY_RT =
PERIODIC_AUCT_ON_DMD_THEO_PX_RT =
CHG_NET_REG_SES_PRV_RG_SES_CL_RT =
CHG_PCT_REG_SES_PRV_RG_SES_CL_RT =
ACTUAL_TRADED_PRICE_RT =
MIN_DYNMC_BID_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_BID_ORDR_LIMT_PX_RT =
MIN_DYNMC_ASK_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_ASK_ORDR_LIMT_PX_RT =
MKTDATA_EVENT_TYPE = SUMMARY
MKTDATA_EVENT_SUBTYPE = NEWDAY
DELTA_AVAT_30_DAY_INTERVAL =
DELTA_AVAT_1_DAY_INTERVAL =
DELTA_AVAT_5_DAY_INTERVAL =
DELTA_AVAT_10_DAY_INTERVAL =
DELTA_AVAT_20_DAY_INTERVAL =
DELTA_AVAT_100_DAY_INTERVAL =
DELTA_AVAT_180_DAY_INTERVAL =
DELTA_ATAT_1_DAY_INTERVAL =
DELTA_ATAT_5_DAY_INTERVAL =
DELTA_ATAT_10_DAY_INTERVAL =
DELTA_ATAT_20_DAY_INTERVAL =
DELTA_ATAT_30_DAY_INTERVAL =
DELTA_ATAT_100_DAY_INTERVAL =
DELTA_ATAT_180_DAY_INTERVAL =
REALTIME_15_SEC_PRICE_PCT_CHG =
REALTIME_ONE_MIN_PRICE_PCT_CHG =
REALTIME_FIVE_MIN_PRICE_PCT_CHG =
REALTIME_15_MIN_PRICE_PCT_CHG =
REALTIME_ONE_HOUR_PRICE_PCT_CHG =
REALTIME_VOLUME_5_DAY_INTERVAL =
CURRENT_SESSION_RT = 4
IMPLIED_BID_PRICE_RT =
IMPLIED_ASK_PRICE_RT =
IMPLIED_BID_SIZE_RT =
IMPLIED_ASK_SIZE_RT =
IS_DELAYED_STREAM = false
}
}
I use this to check the datetime and emit a trade event:
if (message.HasElement(LAST_TIME))
{
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
{
DateTime time = message.GetElementAsDatetime(LAST_TIME).ToSystemDateTime();
if (message.HasElement(LAST) && message.HasElement(SIZE))
{
double last = message.GetElementAsFloat64(LAST);
int last_size = message.GetElementAsInt32(SIZE);
long volume = message.GetElementAsInt64(VOLUME); ...
I receive:
'Bloomberglp.Blpapi.NotFoundException: LAST_TRADE_PRICE_TIME_TODAY_RT has no value in MarketDataUpdate.'
I have tried converting to string first and checking if empty and checking null. Any ideas would be helpful...
I don't think checking the DataType is what you want. The
DataType is part of the schema. It should always be set even when there is no value. If it seems to be working, it is possibly because the element's data type is not DATETIME. For instance, if it is of type DATE, or TIME, GetAsDateTime would still work, but the DataType will never be DATETIME—meaning the code path will never get hit. What you want to check is if it has a value.
HasElement is saying that the schema contains such an element, but if the schema definition allows for there to be zero values (optional), it might not have a value. GetValueAsDatetime() is really GetValueAsDatetime(0), meaning the 0th value which may not exist. Note the same function can be used for array type items that have more than one value. I think the correct way to check this would be:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.NumValues > 0) {
DateTime dt = lastTime.GetValueAsDatetime();
I suspect that
if (message.HasElement(LAST_TIME))
returns true because the field is there (but empty). However when you call:
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
GetElementAsDatetime throws an exception because the value (which is empty) is not a valid datetime.
I think something like this may work:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.Datatype() == Schema.Datatype.DATETIME) {
DateTime dt = lastTime.GetValueAsDatetime();
I am trying to insert it into the database via LINQ-SQL. I am trying the following
using(DataContext obj = new DataContext())
{
mdc_meters_data data = new mdc_meters_data();
data.cust_id = cust_id;
data.device_id = Convert.ToString(device_id);
data.kwh = Convert.ToString(e_val);
data.voltage_p1 = Convert.ToString(a_vol_val);
data.voltage_p2 = Convert.ToString(b_vol_val);
data.voltage_p2 = Convert.ToString(c_vol_val);
data.current_p1 = Convert.ToString(a_curr_val);
data.current_p2 = Convert.ToString(b_curr_val);
data.current_p3 = Convert.ToString(c_curr_val);
data.data_date_time = Convert.ToDateTime(theDate.ToString(format));
data.d_type = Convert.ToString(d_type);
data.pf1 = Convert.ToString(a_pf_val);
data.pf2 = Convert.ToString(b_pf_val);
data.pf3 = Convert.ToString(c_pf_val);
data.p_id = p_id;
// executes the commands to implement the changes to the database
obj.SubmitChanges();
}
The error I am getting is
'DataContext' does not contain a definition for 'SubmitChanges' and no accessible extension method 'SubmitChanges' accepting a first argument of type 'DataContext' could be found
Update 1
I was doing it wrong so I tried to do it with my class which inherits DbContext class. But for an unknown reason, it's still not inserting the data
using(mdc_dbEntities obj = new mdc_dbEntities())
{
mdc_meters_data data = new mdc_meters_data();
data.cust_id = cust_id;
data.device_id = Convert.ToString(device_id);
data.kwh = Convert.ToString(e_val);
data.voltage_p1 = Convert.ToString(a_vol_val);
data.voltage_p2 = Convert.ToString(b_vol_val);
data.voltage_p2 = Convert.ToString(c_vol_val);
data.current_p1 = Convert.ToString(a_curr_val);
data.current_p2 = Convert.ToString(b_curr_val);
data.current_p3 = Convert.ToString(c_curr_val);
data.data_date_time = Convert.ToDateTime(theDate.ToString(format));
data.d_type = Convert.ToString(d_type);
data.pf1 = Convert.ToString(a_pf_val);
data.pf2 = Convert.ToString(b_pf_val);
data.pf3 = Convert.ToString(c_pf_val);
data.p_id = p_id;
// executes the commands to implement the changes to the database
obj.SaveChanges();
}
I want to get my linq query result back as json format. I have been searching for hours.
Here is my code :
public IEnumerable<callersW> GetAllCallersF()
{
testCDREntities1 context = this.CurrentDataSource;
var query = (
from oneCaller in CurrentDataSource.TestTables
select new
{
Created = oneCaller.Created,
Answered = oneCaller.Answered,
Destroyed = oneCaller.Destroyed,
CallerID = oneCaller.CallerId,
CalledID = oneCaller.CalledId,
DisconnectionCode = oneCaller.DisconnectionCode,
RTP_Caller_G107MOS = oneCaller.RTP_Caller_G107MOS,
RTP_Caller_LostPackets = oneCaller.RTP_Caller_LostPackets,
RTP_Caller_MaxRfc3550Jitter = oneCaller.RTP_Caller_MaxRfc3550Jitter,
RTP_Caller_MeanRfc3550Jitter = oneCaller.RTP_Caller_MeanRfc3550Jitter,
RTP_Called_G107MOS = oneCaller.RTP_Called_G107MOS,
RTP_Called_LostPackets = oneCaller.RTP_Called_LostPackets,
RTP_Called_MaxRfc3550Jitter = oneCaller.RTP_Called_MaxRfc3550Jitter,
RTP_Called_MeanRfc3550Jitter = oneCaller.RTP_Called_MeanRfc3550Jitter,
}).ToList()
.Select(x => new callersW
{
Created = Convert.ToDateTime(x.Created),
Answered = Convert.ToDateTime(x.Answered),
Destroyed = Convert.ToDateTime(x.Destroyed),
CallerID = x.CallerID,
CalledID = x.CalledID,
DisconnectionCode = Convert.ToInt32(x.DisconnectionCode),
RTP_Caller_G107MOS = Convert.ToDouble(x.RTP_Caller_G107MOS),
RTP_Caller_LostPackets = Convert.ToDouble(x.RTP_Caller_LostPackets),
RTP_Caller_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MaxRfc3550Jitter),
RTP_Caller_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MeanRfc3550Jitter),
RTP_Called_G107MOS = Convert.ToDouble(x.RTP_Called_G107MOS),
RTP_Called_LostPackets = Convert.ToDouble(x.RTP_Called_LostPackets),
RTP_Called_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MaxRfc3550Jitter),
RTP_Called_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MeanRfc3550Jitter)
}).ToList();
return query;
}
Can somebody help me with this ?
Add to your project JSON.NET and serialize object eg:
string json = JsonConvert.SerializeObject(query);
More examples here.
I have some code that is using the following xml file. Can someone tell me why my doc.Descendants is returning null?
Here is the XML File:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<EmployerTPASeparationResponseCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://uidataexchange.org/schemas SeparationResponse.xsd" xmlns="https://uidataexchange.org/schemas">
<EmployerTPASeparationResponse>
<StateRequestRecordGUID>94321098761987654321323456109883</StateRequestRecordGUID>
<BrokerRecordTransactionNumber>123456789</BrokerRecordTransactionNumber>
<SSN>999999999</SSN>
<ClaimEffectiveDate>2011-02-09</ClaimEffectiveDate>
<ClaimNumber>1234568010</ClaimNumber>
<StateEmployerAccountNbr>12345689</StateEmployerAccountNbr>
<ClaimantJobTitle>Assistant Manager</ClaimantJobTitle>
<EmployerReportedClaimantFirstDayofWork>2009-02-02</EmployerReportedClaimantFirstDayofWork>
<EmployerReportedClaimantLastDayofWork>2010-03-16</EmployerReportedClaimantLastDayofWork>
<TotalEarnedWagesNeededInd>2</TotalEarnedWagesNeededInd>
<TotalEarnedWages>15000.00</TotalEarnedWages>
<WagesEarnedAfterClaimEffectiveDate>20000.00</WagesEarnedAfterClaimEffectiveDate>
<NumberOfHoursWorkedAfterClaimEffectiveDate>80</NumberOfHoursWorkedAfterClaimEffectiveDate>
<AverageWeeklyWage>10.00</AverageWeeklyWage>
<EmployerSepReasonCode>2</EmployerSepReasonCode>
<EmployerSepReasonComments>Expected return date back to work is 4/25/11</EmployerSepReasonComments>
<PreparerTypeCode>T</PreparerTypeCode>
<PreparerCompanyName>Barnett Associates</PreparerCompanyName>
<PreparerTelephoneNumberPlusExt>5555555555</PreparerTelephoneNumberPlusExt>
<PreparerContactName>Diana Turkoane</PreparerContactName>
<PreparerTitle>CSR</PreparerTitle>
<PreparerFaxNbr>5555555555</PreparerFaxNbr>
<PreparerEmailAddress>asdf#asdf.com</PreparerEmailAddress>
</EmployerTPASeparationResponse>
<EmployerTPASeparationResponse>
<StateRequestRecordGUID>94321098761987654321323456109884</StateRequestRecordGUID>
<BrokerRecordTransactionNumber>123456789</BrokerRecordTransactionNumber>
<SSN>999999999</SSN>
<ClaimEffectiveDate>2011-02-10</ClaimEffectiveDate>
<ClaimNumber>1234568010</ClaimNumber>
<StateEmployerAccountNbr>12345689</StateEmployerAccountNbr>
<ClaimantJobTitle>Assistant Manager</ClaimantJobTitle>
<EmployerReportedClaimantFirstDayofWork>2009-02-03</EmployerReportedClaimantFirstDayofWork>
<EmployerReportedClaimantLastDayofWork>2010-03-17</EmployerReportedClaimantLastDayofWork>
<EmployerSepReasonCode>2</EmployerSepReasonCode>
<EmployerSepReasonComments>Expected return date back to work is 4/30/11</EmployerSepReasonComments>
<PreparerTypeCode>T</PreparerTypeCode>
<PreparerCompanyName>Barnett Associates</PreparerCompanyName>
<PreparerTelephoneNumberPlusExt>5555555555</PreparerTelephoneNumberPlusExt>
<PreparerContactName>Diana Turkoane</PreparerContactName>
<PreparerTitle>CSR</PreparerTitle>
<PreparerFaxNbr>5555555555</PreparerFaxNbr>
<PreparerEmailAddress>asdf#asdf.com</PreparerEmailAddress>
</EmployerTPASeparationResponse>
</EmployerTPASeparationResponseCollection>
Here is the code I am using. I first use some Linq to get the Anonymous values, then try to loop through each child node and populate with cmd.parameters.
Here is the code:
XDocument doc = XDocument.Load("XmlString.xml");
var EmployerTPASeparationResponse =
from node in doc.Descendants("EmployerTPASeparationResponse")
select new
{
param1 = node.Element("StateRequestRecordGUID").Value,
param2 = node.Element("BrokerRecordTransactionNumber").Value,
param3 = node.Element("SSN").Value,
param4 = node.Element("ClaimEffectiveDate").Value,
param5 = node.Element("ClaimNumber").Value,
param6 = node.Element("StateEmployerAccountNbr").Value,
param7 = node.Element("CorrectedEmployerName").Value,
param8 = node.Element("CorrectedStateEmployerAccountNbr").Value,
param9 = node.Element("CorrectedFEIN").Value,
param10 = node.Element("OtherSSN").Value,
param11 = node.Element("ClaimantNameWorkedAsForEmployers").Value,
param12 = node.Element("ClaimantJobTitle").Value,
param13 = node.Element("SeasonalEmploymentInd").Value,
param14 = node.Element("EmployerReportedClaimantFirstDayofWork").Value,
param15 = node.Element("EmployerReportedClaimantLastDayofWork").Value,
param16 = node.Element("EffectiveSeparationDate").Value,
param17 = node.Element("TotalEarnedWagesNeededInd").Value,
param18 = node.Element("TotalEarnedWages").Value,
param19 = node.Element("TotalWeeksWorkedNeededInd").Value,
param20 = node.Element("TotalWeeksWorked").Value,
param21 = node.Element("WagesEarnedAfterClaimEffectiveDate").Value,
param22 = node.Element("NumberOfHoursWorkedAfterClaimEffectiveDate").Value,
param23 = node.Element("AverageWeeklyWage").Value,
param24 = node.Element("EmployerSepReasonCode").Value,
param25 = node.Element("ReturnToWorkInd").Value,
param26 = node.Element("ReturnToWorkDate").Value,
param27 = node.Element("WorkingAllAvailableHoursInd").Value,
param28 = node.Element("NotWorkingAvailableHoursReason").Value,
param29 = node.Element("DischargeReasonCode").Value,
param30 = node.Element("FinalIncidentReason").Value,
param31 = node.Element("FinalIncidentDate").Value,
param32 = node.Element("ViolateCompanyPolicyInd").Value,
param33 = node.Element("DischargePolicyAwareInd").Value,
param34 = node.Element("DischargePolicyAwareExplanationCode").Value,
param35 = node.Element("WhoDischargedName").Value,
param36 = node.Element("WhoDischargedTitle").Value,
param37 = node.Element("DischargeReasonComments").Value,
param38 = node.Element("VoluntarySepReasonCode").Value,
param39 = node.Element("HiringAgreementChangesCode").Value,
param40 = node.Element("HiringAgreementChangeComments").Value,
param41 = node.Element("ClaimantActionstoAvoidQuitInd").Value,
param42 = node.Element("ActionTakenComments").Value,
param43 = node.Element("ContinuingWorkAvailableInd").Value,
param44 = node.Element("VoluntarySepReasonComments").Value,
param45 = node.Element("AmendedResponse").Value,
param46 = node.Element("AmendedResponseDescription").Value,
param47 = node.Element("EmployerSepReasonComments").Value,
param48 = node.Element("LaborDisputeTypeInd").Value,
param49 = node.Element("AttachmentID").Value,
param50 = node.Element("MandatoryRetirementInd").Value,
param51 = node.Element("PriorIncidentID").Value,
param52 = node.Element("PreparerTypeCode").Value,
param53 = node.Element("PreparerCompanyName").Value,
param54 = node.Element("PreparerTelephoneNumberPlusExt").Value,
param55 = node.Element("PreparerContactName").Value,
param56 = node.Element("PreparerTitle").Value,
param57 = node.Element("PreparerFaxNbr").Value,
param58 = node.Element("PreparerEmailAddress").Value,
};
foreach (var node in EmployerTPASeparationResponse)
{
cmd4.Parameters["StateRequestRecordGUID"].Value = node.param1;
cmd4.Parameters["BrokerRecordTransactionNumber"].Value = node.param2;
cmd4.Parameters["SSN"].Value = node.param3;
cmd4.Parameters["ClaimEffectiveDate"].Value = node.param4;
cmd4.Parameters["ClaimNumber"].Value = node.param5;
cmd4.Parameters["StateEmployerAccountNbr"].Value = node.param6;
cmd4.Parameters["CorrectedEmployerName"].Value = node.param7;
cmd4.Parameters["CorrectedStateEmployerAccountNbr"].Value = node.param8;
cmd4.Parameters["CorrectedFEIN"].Value = node.param9;
cmd4.Parameters["OtherSSN"].Value = node.param10;
cmd4.Parameters["ClaimantNameWorkedAsForEmployers"].Value = node.param11;
cmd4.Parameters["ClaimantJobTitle"].Value = node.param12;
cmd4.Parameters["SeasonalEmploymentInd"].Value = node.param13;
cmd4.Parameters["EmployerReportedClaimantFirstDayofWork"].Value = node.param14;
cmd4.Parameters["EmployerReportedClaimantLastDayofWork"].Value = node.param15;
cmd4.Parameters["EffectiveSeparationDate"].Value = node.param16;
cmd4.Parameters["TotalEarnedWagesNeededInd"].Value = node.param17;
cmd4.Parameters["TotalEarnedWages"].Value = node.param18;
cmd4.Parameters["TotalWeeksWorkedNeededInd"].Value = node.param19;
cmd4.Parameters["TotalWeeksWorked"].Value = node.param20;
cmd4.Parameters["WagesEarnedAfterClaimEffectiveDate"].Value = node.param21;
cmd4.Parameters["NumberOfHoursWorkedAfterClaimEffectiveDate"].Value = node.param22;
cmd4.Parameters["AverageWeeklyWage"].Value = node.param23;
cmd4.Parameters["EmployerSepReasonCode"].Value = node.param24;
cmd4.Parameters["ReturnToWorkInd"].Value = node.param25;
cmd4.Parameters["ReturnToWorkDate"].Value = node.param26;
cmd4.Parameters["WorkingAllAvailableHoursInd"].Value = node.param27;
cmd4.Parameters["NotWorkingAvailableHoursReason"].Value = node.param28;
cmd4.Parameters["DischargeReasonCode"].Value = node.param29;
cmd4.Parameters["FinalIncidentReason"].Value = node.param30;
cmd4.Parameters["FinalIncidentDate"].Value = node.param31;
cmd4.Parameters["ViolateCompanyPolicyInd"].Value = node.param32;
cmd4.Parameters["DischargePolicyAwareInd"].Value = node.param33;
cmd4.Parameters["DischargePolicyAwareExplanationCode"].Value = node.param34;
cmd4.Parameters["WhoDischargedName"].Value = node.param35;
cmd4.Parameters["WhoDischargedTitle"].Value = node.param36;
cmd4.Parameters["DischargeReasonComments"].Value = node.param37;
cmd4.Parameters["VoluntarySepReasonCode"].Value = node.param38;
cmd4.Parameters["HiringAgreementChangesCode"].Value = node.param39;
cmd4.Parameters["HiringAgreementChangeComments"].Value = node.param40;
cmd4.Parameters["ClaimantActionstoAvoidQuitInd"].Value = node.param41;
cmd4.Parameters["ActionTakenComments"].Value = node.param42;
cmd4.Parameters["ContinuingWorkAvailableInd"].Value = node.param43;
cmd4.Parameters["VoluntarySepReasonComments"].Value = node.param44;
cmd4.Parameters["AmendedResponse"].Value = node.param45;
cmd4.Parameters["AmendedResponseDescription"].Value = node.param46;
cmd4.Parameters["EmployerSepReasonComments"].Value = node.param47;
cmd4.Parameters["LaborDisputeTypeInd"].Value = node.param48;
cmd4.Parameters["AttachmentID"].Value = node.param49;
cmd4.Parameters["MandatoryRetirementInd"].Value = node.param50;
cmd4.Parameters["PriorIncidentID"].Value = node.param51;
cmd4.Parameters["PreparerTypeCode"].Value = node.param52;
cmd4.Parameters["PreparerCompanyName"].Value = node.param53;
cmd4.Parameters["PreparerTelephoneNumberPlusExt"].Value = node.param54;
cmd4.Parameters["PreparerContactName"].Value = node.param55;
cmd4.Parameters["PreparerTitle"].Value = node.param56;
cmd4.Parameters["PreparerFaxNbr"].Value = node.param57;
cmd4.Parameters["PreparerEmailAddress"].Value = node.param58;
cmd4.ExecuteNonQuery();
if (cmd4 != null)
{
cmd4 = null;
}
}
You need to include the namespace (xmlns) in all of the element names:
XNamespace ns = "https://uidataexchange.org/schemas";
doc.Descendants(ns + "EmployerTPASeparationResponse")
(And in all of the Element calls)
Note that your code can be made dramatically shorter by looping through the child elements and adding parameters with their names instead of using anonymous types.
For example:
var node = doc.Descendants(ns + "EmployerTPASeparationResponse").Single();
using (cmd4) {
foreach(var param in node.Elements()) {
cmd4.Parameters.AddWithValue(param.Name.LocalName, param.Value);
}
cmd4.ExecuteNonQuery();
}