I am trying to add a product to my DB, I need to get the category ID from another table, however i am not sure how i can do this?
Basically, i have a table with all my different categories in, and i need to pass over the text from my external web service, which will then hit the DB and get the ID of the cat its meant to be in.
Below is the code i have:
using (aboDataDataContext dc = new aboDataDataContext())
{
var match = (from t in dc.tweProducts
where t.sku == productSku
select t).FirstOrDefault();
if (match == null)
{
tweProduct tprod = new tweProduct()
{
sku = p.productcode,
categoryId = Convert.ToInt32(catid),
title = p.name,
brand = p.manufacturer,
description = p.description,
twePrice = p.price,
weight = decimal.TryParse(p.size, out weight) == true ? (int?)weight : null,
size = decimal.TryParse(p.size, out weight) == true ? (int?)weight : null,
contry = p.country,
region = p.region,
vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null,
strength = p.strength,
bottler = p.bottler,
age = int.TryParse(p.age, out age) == true ? (int?)age : null,
caskType = p.casktype,
series = p.series,
flavour = p.flavour,
stock = p.freestock,
tweUpdated = false,
stockUpdated = false,
priceUpdated = false,
dataUpdated = false,
imgPublished = false,
lastUpdated = DateTime.Now,
};
}
}
SO basically the category from the web service is passing in Category_1 (for example), I need to pass this to my DB, to get the ID for Category_1 (say its 1) then insert it into my table.
You need to use FirstOrDefault(), assuming you are getting valid, not null response from your webservice.
categoryId = Convert.ToInt32((from c in dc.Categories
where c.Name == p.category
select c.Id).FirstOrDefault()),
FirstOrDefault/First/SingleOrDefault/Single accepts a predicate:
categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
Related
I need to build a search query with dynamic parameters in net core 3.0.
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
I would like to add search parameters like user name, items type, cars model and data from user. I tried to add "where" before 'select new UserDto' but not always user will provide all search parameters. If I give below:
if(fromSearch.UserName != null && fromSearch.UserName.Lenght > 0)
{
query = query.Where(u => u.Name == fromSearch.UserName);
}
it works(on user.data does not work) but is it correct? How to do this in linq query?
Do something like this:
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id;
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
if(!string.IsNullOrWhitespace(username))
query = query.Where(ud => ud.Name == username);
if(!string.IsNullOrWhitespace(itemtype))
query = query.Where(ud => ud.Items.Any(i => i.Type == itemtype));
if(!string.IsNullOrWhitespace(carmodel))
query = query.Where(ud => ud.Cars.Any(c => c.Model == carmodel));
etc. These will work like AND; if you specify a username and an itemtype you get only those users named that, with that item type somewhere in the items list.. etc
Here is my attempt to make a many to many linq request, but it doesn't work as expected. CVVM class has a property ICollection<FormationVM> Formations
var cv = (
from c in context.CVs
where c.Id == id
select new CVVM
{
Id = id,
Formations =
from f in context.Formations
from c2 in context.CVs
where c2.Id == id
select new FormationVM
{
Id = form.Id,
DateDebut = form.DateDebut,
DateFin = form.DateFin,
Ecole = form.Ecole,
Description = form.Description,
Diplome = form.Diplome
}
}).FirstOrDefault();
Why does Model.Formations.Count() return 3 instead of 2 in my View please ?
Ok i found the solution. This code works :
using (Context context = new Context())
{
var cv =
(
from c in context.CVs
where c.Id == id && c.PersonneId == userId
select new CVVM
{
Titre = c.Titre,
MontrerPhoto = c.MontrerPhoto,
Layout = c.Layout,
Id = id,
FormAction = "EditionTraitement",
FormTitre = "Edition de ce CV",
Formations = from form in c.Formations
where c.Id == id && c.PersonneId == userId
select new FormationVM
{
Id = form.Id,
DateDebut = form.DateDebut,
DateFin = form.DateFin,
Ecole = form.Ecole,
Description = form.Description,
Diplome = form.Diplome
}
}).FirstOrDefault();
}
I have a query, it needs to select from a DB2 DB but the records need to be grouped by one column (PeopleID) so that the Applications can be put into a list for returning the required Data Object. Whilst I can see multiple areas that create CASE statements, I do not see any returning different values.
I have gone through the resulting query that is sent to DB2, it generates the same error but I cannot find anything obvious in that either. I would post the resulting query here but it goes over the character limit.
I have been combing this code and the resulting DB2 query for the last two days and cannot find the source of the data-type mismatch.
In the joins I do have to cast some Non-Nullable values to Nullable, I cannot see any reason that would create conflict.
Error
SQL Error [42804]: The data types of the result-expressions of a CASE expression or DECODE function are not compatible.. SQLCODE=-581, SQLSTATE=42804, DRIVER=4.21.29
The data types of the result-expressions of a CASE expression or DECODE function are not compatible.. SQLCODE=-581, SQLSTATE=42804, DRIVER=4.21.29
An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-581", SQLSTATE "42804" and message tokens "42804".. SQLCODE=-727, SQLSTATE=56098, DRIVER=4.21.29
C# LINQ Query
IEnumerable<PersonRegistrationInformation> results = (from data in (from participant_app in DBContext.PARTICIPANT_APPLICATION
join people_vendor in DBContext.PEOPLE_VENDORS on participant_app.PEOPLE_ID equals people_vendor.PEOPLE_VENDORS_ID into tmppeople_vendor
from people_vendor in tmppeople_vendor.DefaultIfEmpty()
join reg_member_supp_app in DBContext.REG_MEMBER_SUPP_APP
on new { REG_MEMBER_SUPP_APP_ID = (participant_app.REG_MEMBER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_member_supp_app.REG_MEMBER_SUPP_APP_ID, reg_member_supp_app.ELIG_DECISION_ICD } into tmpreg_member
from reg_member_supp_app in tmpreg_member.DefaultIfEmpty()
join reg_trainer_supp_app in DBContext.REG_TRAINER_SUPP_APP
on new { REG_TRAINER_SUPP_APP_ID = (participant_app.REG_TRAINER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_trainer_supp_app.REG_TRAINER_SUPP_APP_ID, reg_trainer_supp_app.ELIG_DECISION_ICD } into tmpreg_trainer
from reg_trainer_supp_app in tmpreg_trainer.DefaultIfEmpty()
where reg_member_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
&& reg_trainer_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
select new PersonRegistrationInformationTableInformation()
{
PeopleID = !string.IsNullOrEmpty(participant_app.PEOPLE_ID) ? participant_app.PEOPLE_ID.ToUpper().Trim() : null,
FirstName = !string.IsNullOrEmpty(people_vendor.FIRST_NAME) ? people_vendor.FIRST_NAME.Trim() : null,
LastName = !string.IsNullOrEmpty(people_vendor.LAST_NAME) ? people_vendor.LAST_NAME.Trim() : null,
RegistryMemberSupplementApplication = reg_member_supp_app,
RegistryTrainerSupplementApplication = reg_trainer_supp_app,
})
group data by data.PeopleID into grp_data
select new PersonRegistrationInformation()
{
PeopleID = grp_data.Key,
FirstName = grp_data.FirstOrDefault().FirstName,
LastName = grp_data.FirstOrDefault().LastName,
RegistryMemberApplications = grp_data.Select(data => new RegistryMemberSupplementApplication()
{
RegistryMemberSupplementApplicationID = data.RegistryMemberSupplementApplication.REG_MEMBER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryMemberSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryMemberSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryMemberSupplementApplication.APPLICANT_SIGNED_DATE,
ParentSignedDate = data.RegistryMemberSupplementApplication.PARENT_SIGNED_DATE,
BasicTranscriptReviewICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_REVIEW_ICD,
BasicTranscriptStatusICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_STATUS_ICD,
TranscriptsReadyDate = data.RegistryMemberSupplementApplication.TRANSCRIPTS_READY_DATE,
SubmitPreviousTrainingICD = data.RegistryMemberSupplementApplication.SUBMIT_PREV_TRAIN_ICD,
HowLearnICD = data.RegistryMemberSupplementApplication.HOW_LEARN_ICD,
IsRenewal = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RENEWAL_FG) ? (bool?)data.RegistryMemberSupplementApplication.RENEWAL_FG.ToUpper().Trim().Equals("Y") : null,
IsReconsideration = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RECONSIDERATION_FG) ? (bool?)data.RegistryMemberSupplementApplication.RECONSIDERATION_FG.ToUpper().Trim().Equals("Y") : null,
ReleaseOfInformationICD = data.RegistryMemberSupplementApplication.RELEASE_INFO_ICD,
PersonJobID = data.RegistryMemberSupplementApplication.PERSON_JOB_ID,
EligibilityDecisionICD = data.RegistryMemberSupplementApplication.ELIG_DECISION_ICD,
EligibilityDenialReasonICD = data.RegistryMemberSupplementApplication.ELIG_DENIAL_REASON_ICD,
EligibilityDecisionDate = data.RegistryMemberSupplementApplication.ELIG_DECISION_DATE,
CurrentEligibilityDate = data.RegistryMemberSupplementApplication.CURR_ELIG_DATE,
RenewEligibilityDate = data.RegistryMemberSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryMemberSupplementApplication.RENEW_NOTICE_DATE,
ParticipantApplicationID = data.RegistryMemberSupplementApplication.PARTICIPANT_APPLICATION_ID,
PendingType = data.RegistryMemberSupplementApplication.PENDING_TYPE,
ReferringProgram = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.REFERRING_PROGRAM) ? data.RegistryMemberSupplementApplication.REFERRING_PROGRAM.Trim() : null,
BTRCompletedDate = data.RegistryMemberSupplementApplication.BTR_COMPLETED_DATE,
CreateDate = data.RegistryMemberSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.CREATE_USER) ? data.RegistryMemberSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryMemberSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.UPDATE_USER) ? data.RegistryMemberSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryMemberSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
}),
RegistryTrainerApplications = grp_data.Select(data=> new RegistryTrainerSupplementApplication()
{
RegistryTrainerSupplementApplicationID = data.RegistryTrainerSupplementApplication.REG_TRAINER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryTrainerSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryTrainerSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryTrainerSupplementApplication.APPLICANT_SIGNED_DATE,
ReleaseOfInformationICD = data.RegistryTrainerSupplementApplication.RELEASE_INFO_ICD,
EligibilityDecisionICD = data.RegistryTrainerSupplementApplication.ELIG_DECISION_ICD,
EligibilityDecisionDate = data.RegistryTrainerSupplementApplication.ELIG_DECISION_DATE,
EligibilityDenialReasonICD = data.RegistryTrainerSupplementApplication.ELIG_DENIAL_REASON_ICD,
RenewEligibilityDate = data.RegistryTrainerSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryTrainerSupplementApplication.RENEW_NOTICE_DATE,
TrainerID = data.RegistryTrainerSupplementApplication.TRAINER_ID,
PendingType = data.RegistryTrainerSupplementApplication.PENDING_TYPE,
CurrentEligibilityDate = data.RegistryTrainerSupplementApplication.CURR_ELIG_DATE,
CreateDate = data.RegistryTrainerSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.CREATE_USER) ? data.RegistryTrainerSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryTrainerSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.UPDATE_USER) ? data.RegistryTrainerSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryTrainerSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
})
}).AsEnumerable();
I seperated out the two linq queries and it appears to work just fine...
IEnumerable<PersonRegistrationInformationTableInformation> results = (from data in (from participant_app in DBContext.PARTICIPANT_APPLICATION
join people_vendor in DBContext.PEOPLE_VENDORS on participant_app.PEOPLE_ID equals people_vendor.PEOPLE_VENDORS_ID into tmppeople_vendor
from people_vendor in tmppeople_vendor.DefaultIfEmpty()
join reg_member_supp_app in DBContext.REG_MEMBER_SUPP_APP
on new { REG_MEMBER_SUPP_APP_ID = (participant_app.REG_MEMBER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_member_supp_app.REG_MEMBER_SUPP_APP_ID, reg_member_supp_app.ELIG_DECISION_ICD } into tmpreg_member
from reg_member_supp_app in tmpreg_member.DefaultIfEmpty()
join reg_trainer_supp_app in DBContext.REG_TRAINER_SUPP_APP
on new { REG_TRAINER_SUPP_APP_ID = (participant_app.REG_TRAINER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_trainer_supp_app.REG_TRAINER_SUPP_APP_ID, reg_trainer_supp_app.ELIG_DECISION_ICD } into tmpreg_trainer
from reg_trainer_supp_app in tmpreg_trainer.DefaultIfEmpty()
where reg_member_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
&& reg_trainer_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
select new PersonRegistrationInformationTableInformation()
{
PeopleID = !string.IsNullOrEmpty(participant_app.PEOPLE_ID) ? participant_app.PEOPLE_ID.ToUpper().Trim() : null,
FirstName = !string.IsNullOrEmpty(people_vendor.FIRST_NAME) ? people_vendor.FIRST_NAME.Trim() : null,
LastName = !string.IsNullOrEmpty(people_vendor.LAST_NAME) ? people_vendor.LAST_NAME.Trim() : null,
RegistryMemberSupplementApplication = reg_member_supp_app,
RegistryTrainerSupplementApplication = reg_trainer_supp_app,
})
IEnumerable<PersonRegistrationInformation> tableinfo = from data in results
group data by data.PeopleID into grp_data
select new PersonRegistrationInformation()
{
PeopleID = grp_data.Key,
FirstName = grp_data.FirstOrDefault().FirstName,
LastName = grp_data.FirstOrDefault().LastName,
RegistryMemberApplications = grp_data.Select(data => new RegistryMemberSupplementApplication()
{
RegistryMemberSupplementApplicationID = data.RegistryMemberSupplementApplication.REG_MEMBER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryMemberSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryMemberSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryMemberSupplementApplication.APPLICANT_SIGNED_DATE,
ParentSignedDate = data.RegistryMemberSupplementApplication.PARENT_SIGNED_DATE,
BasicTranscriptReviewICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_REVIEW_ICD,
BasicTranscriptStatusICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_STATUS_ICD,
TranscriptsReadyDate = data.RegistryMemberSupplementApplication.TRANSCRIPTS_READY_DATE,
SubmitPreviousTrainingICD = data.RegistryMemberSupplementApplication.SUBMIT_PREV_TRAIN_ICD,
HowLearnICD = data.RegistryMemberSupplementApplication.HOW_LEARN_ICD,
IsRenewal = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RENEWAL_FG) ? (bool?)data.RegistryMemberSupplementApplication.RENEWAL_FG.ToUpper().Trim().Equals("Y") : null,
IsReconsideration = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RECONSIDERATION_FG) ? (bool?)data.RegistryMemberSupplementApplication.RECONSIDERATION_FG.ToUpper().Trim().Equals("Y") : null,
ReleaseOfInformationICD = data.RegistryMemberSupplementApplication.RELEASE_INFO_ICD,
PersonJobID = data.RegistryMemberSupplementApplication.PERSON_JOB_ID,
EligibilityDecisionICD = data.RegistryMemberSupplementApplication.ELIG_DECISION_ICD,
EligibilityDenialReasonICD = data.RegistryMemberSupplementApplication.ELIG_DENIAL_REASON_ICD,
EligibilityDecisionDate = data.RegistryMemberSupplementApplication.ELIG_DECISION_DATE,
CurrentEligibilityDate = data.RegistryMemberSupplementApplication.CURR_ELIG_DATE,
RenewEligibilityDate = data.RegistryMemberSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryMemberSupplementApplication.RENEW_NOTICE_DATE,
ParticipantApplicationID = data.RegistryMemberSupplementApplication.PARTICIPANT_APPLICATION_ID,
PendingType = data.RegistryMemberSupplementApplication.PENDING_TYPE,
ReferringProgram = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.REFERRING_PROGRAM) ? data.RegistryMemberSupplementApplication.REFERRING_PROGRAM.Trim() : null,
BTRCompletedDate = data.RegistryMemberSupplementApplication.BTR_COMPLETED_DATE,
CreateDate = data.RegistryMemberSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.CREATE_USER) ? data.RegistryMemberSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryMemberSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.UPDATE_USER) ? data.RegistryMemberSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryMemberSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
}),
RegistryTrainerApplications = grp_data.Select(data=> new RegistryTrainerSupplementApplication()
{
RegistryTrainerSupplementApplicationID = data.RegistryTrainerSupplementApplication.REG_TRAINER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryTrainerSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryTrainerSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryTrainerSupplementApplication.APPLICANT_SIGNED_DATE,
ReleaseOfInformationICD = data.RegistryTrainerSupplementApplication.RELEASE_INFO_ICD,
EligibilityDecisionICD = data.RegistryTrainerSupplementApplication.ELIG_DECISION_ICD,
EligibilityDecisionDate = data.RegistryTrainerSupplementApplication.ELIG_DECISION_DATE,
EligibilityDenialReasonICD = data.RegistryTrainerSupplementApplication.ELIG_DENIAL_REASON_ICD,
RenewEligibilityDate = data.RegistryTrainerSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryTrainerSupplementApplication.RENEW_NOTICE_DATE,
TrainerID = data.RegistryTrainerSupplementApplication.TRAINER_ID,
PendingType = data.RegistryTrainerSupplementApplication.PENDING_TYPE,
CurrentEligibilityDate = data.RegistryTrainerSupplementApplication.CURR_ELIG_DATE,
CreateDate = data.RegistryTrainerSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.CREATE_USER) ? data.RegistryTrainerSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryTrainerSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.UPDATE_USER) ? data.RegistryTrainerSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryTrainerSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
})
});
I have used q Linq query and add new one record at top of index of list
List<PMAST> lstPmast = new List<PMAST>();
lstPmast.Add(new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
var GetEmployeeLst = (from d in db.PMASTs
where d.CNO == iCNO && d.Isdeleted != true
select new
{
EmpId = d.EmpId,
PCODE = d.PCODE,
PNAME = d.PNAME
}).ToList();
You can do it in multiple ways, one of them is just use AddRange method of List:
List<PMAST> lstPmast = new List<PMAST>();
lstPmast.Add(new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
var GetEmployeeLst = (from d in db.PMASTs
where d.CNO == iCNO && d.Isdeleted != true
select new
{
EmpId = d.EmpId,
PCODE = d.PCODE,
PNAME = d.PNAME
}).ToList();
lstPmast.AddRange(GetEmployeeLst);
Since your question is tagged with ASP.NET MVC, I assume that you are trying to add some default value to a drop down. If this is the case you could directly use the appropriate DropDownListFor helper which allows you to achieve that without the need of inserting such fake records in your view model:
#Html.DropDownListFor(x => x.SelectedEmployee, Model.Employees, "--Select--")
You no longer need to alter your data model to achieve such purely UI stuff.
Use this instead of Add:
lstPmast.Insert(0,new PMAST() { EmpId = 0, PCODE = "--Select--", PNAME = "--Select--" });
You can add ne record by list.add like :
lstPmast.add(newlistitem);
Looks like your list of objects will end up in either an asp.net combobox or a winform combobox.
Here is my suggestion
List<Tuple<int,string>> lstPmast;
var lstPmast = db.PMASTs.Where(d => d.CNO == iCNO && !d.Isdeleted).Select(d => Tuple.Create(d.EmpId, e.PCODE + "-" + e.PNAME)).ToList();
// then add a default as the first item in the list
lstPmast.Insert(0, Tuple.Create(0, "--- Select ---"));
// bind the list to your combobox here. Use Item1 as value and Item2 as the description
I am having trouble with this I have 3 Data tables i use over and over again which are cached I would like to write a LINQ statement which would do the following is this possible?
T-SQL VERSION:
SELECT P.[CID],P.[AID]
,B.[AID], B.[Data], B.[Status], B.[Language]
FROM MY_TABLE_1 P
JOIN
(
SELECT A.[AID], A.[Data], A.[Status], A.[Language] FROM MY_TABLE_2 A
UNION ALL
SELECT B.[AID], B.[Data], B.[Status], B.[Language] FROM MY_TABLE_3 B
) B on P.[AID] = B.[AID]
WHERE B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1 AND B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1
Then i would like it to create a result set of the following
Results:
|CID|AID|DATA|STATUS|LANGUAGE
Try this:
from p in Context.MyTable1
join b in Contact.MyTable2.Concat(Contact.MyTable3)
on p.aid equals b.aid
where b.Language == "EN" || b.Language == "ANY"
where b.Status == 1
select new
{
p.CID,
p.AID,
b.Data,
b.Status,
b.Language
};
Don't do it this way.
Your two options
Create a view which represents your Union statement (Table2 and Table3)
Create a relationship on the DBML between Table1 and the new view on the AID column.
Do a SelectMany to get your required return result.
or (and preferred)
Create a stored procedure that accepts the language / status (assuming they are parameters) and returns this data set. This will be the most efficient method.
You are doing database work in your business logic! Use the database for what it was intended.
Make sure you reference System.Data.DataSetExtensions, and use the AsEnumerable() method to use LINQ to DataSets.
var myTable1 = new [] {
new { CID = "123", AID = 345, Data = 32323, Status = 1, Language = "EN"},
new { CID = "231", AID = 123, Data = 11525, Status = 2, Language = "EN"},
new { CID = "729", AID = 513, Data = 15121, Status = 1, Language = "ANY"},
new { CID = "231", AID = 123, Data = 54421, Status = 2, Language = "EN"}}
.ToDataTable().AsEnumerable();
var myTable2 = new [] {
new { CID = "512", AID = 513, Data = 32323, Status = 1, Language = "ANY"},
new { CID = "444", AID = 123, Data = 11525, Status = 2, Language = "BLAH"},
new { CID = "222", AID = 333, Data = 15121, Status = 1, Language = "ANY"},
new { CID = "111", AID = 345, Data = 54421, Status = 2, Language = "EN"}}
.ToDataTable().AsEnumerable();
var myTable3 = new [] {
new { CID = "888", AID = 123, Data = 32323, Status = 2, Language = "EN"},
new { CID = "494", AID = 333, Data = 11525, Status = 1, Language = "FR"},
new { CID = "202", AID = 513, Data = 15121, Status = 1, Language = "EN"},
new { CID = "101", AID = 345, Data = 54421, Status = 2, Language = "ANY"}}
.ToDataTable().AsEnumerable();
var q = from p in myTable1
join b in myTable2.Union(myTable3) on p.Field<int>("AID") equals b.Field<int>("AID")
where (b.Field<string>("Language") == "EN" || b.Field<string>("Language") == "ANY") && b.Field<int>("Status") == 1
select new
{
CID = p.Field<string>("CID"),
B_AID = p.Field<int>("AID"),
P_AID = b.Field<int>("AID"),
Data = b.Field<int>("Data"),
Status = b.Field<int>("Status"),
Language = b.Field<string>("Language")
};
var table = q.ToDataTable();
I used an extension method you can find here to test this, it's pretty useful if you are doing a lot of LINQ over DataTables.