is there a way to get rid of DTO - asp.net

I am using Entity Framework. I have the following query in which I get data using two tables Application and Employee connected by a foreign key EmployeeID in Application Table. The tables have 1-1 relationship .
Is there a way to simplify the following code and get rid of the DTO Employee1
which is the same as auto generated Employee class
public List<Employee1> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select new Employee1
{
EmployeeID = e.EmployeeID,
SecondEmail = e.SecondEmail,
EmailID = e.EmailID,
Title = e.Title,
Name = e.Name,
Rank = e.Rank,
POBox = e.POBox,
Phone = e.Phone,
JoinDate = e.JoinDate,
Status = e.Status,
DepartmentID = e.DepartmentID.Value,
NameString = e.NameString,
Department = e.Department,
ParentDept = e.ParentDept,
DepartmentAr = e.DepartmentAr,
NameAr = e.NameAr,
NameStringAr = e.NameStringAr,
TitleAr = e.TitleAr
}).ToList();
return data;
}

If you need to return list of Employees, just select e which refers to Employee and don't use Employee1 as a DTO.
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select e).ToList();
return data;
}
Another way is this, which I would prefer because of readability:
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = context.Applications.Where(p=>p.ApplicationID == ApplicationID).Select(p=>p.Employee).ToList();
return data;
}

Related

How to return this query values

I implement the join query for join two tables. How to return those values.
public List<cartItem> getcartItem(int userId)
{
var data = (from c in _context.cartItems join p in _context.Products
on c.productId equals p.ProId
where c.userId == userId && c.status==false select new {
proName=p.ProductName,
qty=c.quantity,
proImg=p.ImageUrl,
uPricce=p.price
}).ToList();
return data;
}
Assuming these are the properties of a cartItem obj, you just need to assign the select statement to match the return type and new up a cartItem.
...select new cartItem
{
proName = p.ProductName,
qty = c.quantity,
proImg = p.ImageUrl,
uPricce = p.price
}).ToList();

Could not get the data from IQueryable<object>

I have this in my server to fetch data from a database:
[HttpPost]
[Route("api/getaddress")]
public IQueryable<PreAddress> GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
return preAddress;
}
}
This is how I get the data from the client:
service
getAddress() {
const endpoint = this.rootUrl + '/api/getaddress';
const formData: FormData = new FormData();
formData.append('personId', this.genParams.personId);
return this.http.post(endpoint, formData);
}
component
getPersonInformation() {
this.clientService.getPerson(this.genParams.personId)
.subscribe((data: any) => {
console.log(data);
this.person = data;
});
}
Following the server using debugger, I can actually get a value but in my client side. I get the following error:
I need your help. Thank you.
Try updating your code like this:
[HttpPost]
[Route("api/getaddress")]
public PreAddress GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
PreAddress preAddress;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
preAddress = preAddress.FirstOrDefault();
}
return preAddress;
}
You need to execute the IQuerable before you return it, in this scenario try with ToList()
[HttpPost]
[Route("api/getaddress")]
public IEnuerable<PreAddress> GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
return preAddress.ToList(); //invoke it here
}
}

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

How to correctly return from stored procedure in Sql to model?

I need to return list of values from stored procedure to my model. How do I do it:
[HttpGet("{id}")]
public DataSource Get(int id)
{
DataSource ds = _dbContext.DataSources.Where(d => d.Id == id)
.Include(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions).FirstOrDefault();
foreach(DataSourceParam p in ds.DataSourceParams)
{
if(p.TypeId == 5)
{
p.SelectOptions = _dbContext.SelectOptions.FromSql("Exec " + ds.DataBaseName + ".dbo." + "procGetTop50 " + ds.Id + ", 1").ToList();
}
}
return ds;
}
First, declare your procedure with parameters:
string sql = "myProcedure #param1, #param2";
Second, create parameters
var param1 = new SqlParameter { ParameterName = "param1", Value = param1Value};
var param2 = new SqlParameter { ParameterName = "param2", Value = param2Value };
Finally, exec the code:
info = this.DbContext.Database.SqlQuery<MyModel>(sql, param1, param2).FirstOrDefault();
This is it!
Just remember your model must match with the procedure columns. With means, if your procedure returns a column named 'MyProp' your model 'MyModel' must have a 'MyProp' property.

Display result of linq query randomly in listview in Asp.net C#

var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest;
ListView1.DataBind();
How to display result of linq query randomly in listview in Asp.net C#?
You can create a random data by adding a guid property to your query. After that you order the result by this new property.
var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
RandomId = Guid.NewGuid(),
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest.OrderBy(p => p.RandomId).ToList();
ListView1.DataBind();

Resources