Dapper c# Inner join - c#

Hi Im trying do that query in dapper, but the list contatos return with the values null for my class Client, i don't know what i doing wrong. my class Clt_cadCliente is one Client has several contact (clt_cadContatos). Help please.
var lookup = new Dictionary<int, Clt_cadCliente>();
cn.Query<Clt_cadCliente, Clt_cadContatos, Clt_cadCliente>(#"
SELECT s.*, a.*
FROM Clt_cadCliente s
INNER JOIN Clt_cadContatos a ON s.IdCLiente = a.IdCliente ", (s, a) =>
{
Clt_cadCliente shop;
if (!lookup.TryGetValue(s.IdCliente, out shop))
{
lookup.Add(s.IdCliente, shop = s);
}
shop.Clt_cadContatos.Add(a);
return shop;
}, splitOn: "IdCliente").AsQueryable();
var resultList = lookup.Values;
Class:
public partial class Clt_cadCliente
{
public int IdCliente { get; set; }
public Nullable<int> IdClientePai { get; set; }
public string Codigo { get; set; }
public string Nome { get; set; }
public Nullable<System.DateTime> DataNasc { get; set; }
public string Sexo { get; set; }
public Nullable<int> IdEstCivil { get; set; }
public string CPF { get; set; }
public string RG { get; set; }
public Nullable<System.DateTime> DataAdm { get; set; }
public bool Pendencias { get; set; }
public string DescPendencia { get; set; }
public string Obs { get; set; }
public string PessoaFJ { get; set; }
public string NomeFantasia { get; set; }
public string CodDep { get; set; }
public string AtivoInativo { get; set; }
public bool Ativado { get; set; }
public Nullable<int> IdSitBloq { get; set; }
public Nullable<int> SitBloq { get; set; }
public string Profissao { get; set; }
public string Empresa { get; set; }
public string NomeEsposa { get; set; }
public Nullable<System.DateTime> NascEsposa { get; set; }
public Nullable<int> IdNaturezaPadrao { get; set; }
public Nullable<int> ViaCarteirinha { get; set; }
public Nullable<int> Casa { get; set; }
public Nullable<int> Renda { get; set; }
public Nullable<int> RendaComplementar { get; set; }
public string Naturalidade { get; set; }
public string Banco { get; set; }
public string Agencia { get; set; }
public string CidadeBanco { get; set; }
public bool VeiculoProprio { get; set; }
public Nullable<System.DateTime> DIB { get; set; }
public string Foto { get; set; }
public string Nbeneficio { get; set; }
public Nullable<bool> LiberarExame { get; set; }
public Nullable<System.DateTime> ValidadeExame { get; set; }
public Nullable<int> EnviaBoleto { get; set; }
public Nullable<int> IdUsuario { get; set; }
public Nullable<long> IdClienteGlobal { get; set; }
public virtual IList<Clt_cadContatos> Clt_cadContatos { get; set; }
}
Class 2:
public partial class Clt_cadContatos
{
public int IdContato { get; set; }
public string Nome { get; set; }
public string Telefone { get; set; }
public string Email { get; set; }
public bool AdicionarLista { get; set; }
public Nullable<int> IdCliente { get; set; }
}

I cannot test it of course, but I have a similar situation and if you don't insert, at least, the fields of the table Clt_cadContatos and in particular the name of the field IdCliente of this table, then the library cannot resolve the splitOn parameter
var lookup = new Dictionary<int, Clt_cadCliente>();
cn.Query<Clt_cadCliente, Clt_cadContatos, Clt_cadCliente>(#"
SELECT s.*, a.IdCliente, a.OtherField1, a.OtherField2, etc ....
FROM Clt_cadCliente s
INNER JOIN Clt_cadContatos a ON s.IdCLiente = a.IdCliente ", (s, a) =>
{
Clt_cadCliente shop;
if (!lookup.TryGetValue(s.IdCliente, out shop))
{
lookup.Add(s.IdCliente, shop = s);
}
shop.Clt_cadContatos.Add(a);
return shop;
}, splitOn: "IdCliente").AsQueryable();
var resultList = lookup.Values;

You are splitting on the wrong parameter. You need to split on IdContato.
The split on field tells Dapper where one entity ends and the next begins. If you select s.* followed by a.* you want to split into a second entity on the first field of the table a (I'm assuming that your sql tables resemble your classes.)

Related

Including foreign key values into a DTO for a single record

It's been a while since I have done this, but I know there is an easy way to do this that I have forgotten. Below I have a class designed to populate a single record of a data object. But I cannot get the values from another table (related by foreign key) to populate using the lambda statement because I am missing something (the two values being pulled in from another table below can be seen as dto.LeaseName and dto.CarName). How should I write the lambda for the object dm?
public StationUnloadingLogDTO GetSingleRecordforLog(int Id)
{
StationUnloadingLogDTO dto = new StationUnloadingLogDTO();
StationUnloadingLog dm = new StationUnloadingLog();
dm = entity.StationUnloadingLog
.Where(x => x.Id == Id)
.FirstOrDefault();
dto.Id = dm.Id;
dto.DateLogged = dm.DateLogged;
dto.DriverName = dm.DriverName;
dto.TruckNumber = dm.TruckNumber;
dto.CarName = dm.Carrier.CarName;
dto.CarrierId = dm.CarrierId;
dto.SpecificGravity = dm.SpecificGravity;
dto.LactMeterOpen = dm.LactMeterOpen;
dto.LactMeterClose = dm.LactMeterClose;
dto.EstimatedBarrels = dm.EstimatedBarrels;
dto.TicketNumber = dm.TicketNumber;
dto.LeaseNumber = dm.LeaseNumber;
dto.LeaseName = dm.Company.CmpName;
dto.StationId = dm.StationId;
return dto;
}
Here are the related data classes
namespace Data.Models
{
public partial class Company
{
public Company()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CmpId { get; set; }
public string CmpName { get; set; }
public string CmpAddress1 { get; set; }
public string CmpAddress2 { get; set; }
public int? CmpCity { get; set; }
public string CmpZip { get; set; }
public string CmpPrimaryphone { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
public class StationUnloadingLogDTO
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public string CarName { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseName { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
}
public partial class StationUnloadingLog
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
public Carrier Carrier { get; set; }
public Company Company { get; set; }
public Tractorprofile Tractorprofile { get; set; }
}
public partial class Carrier
{
public Carrier()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CarId { get; set; }
public string CarName { get; set; }
public string CarAddress1 { get; set; }
public string CarAddress2 { get; set; }
public int? CtyCode { get; set; }
public string CarZip { get; set; }
public string CarContact { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
You should query for your record with child entities like this.
dm = DbSet<StationUnloadingLog>
.Where(x => x.Id == Id).Include(x => x.Carrrier)
.FirstOrDefault();

Map multiple different models into single View Model - AutoMapper

I am trying to map multiple Userprofile models into a single viewModel. At a time only one user data will be mapped.
In the below code snippet I mentioned the use case that I already tried.
Also, I try to AutoMapper.Map<source,target> but didn't work for me.
//This is one FarmerUser Model
public partial class FarmerProfileModel
{
public long FarmerId { get; set; }
public string FarmerName { get; set; }
public string FatherHusbandName { get; set; }
public string Cnic { get; set; }
public string Gender { get; set; }
public string CellPhone { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateCellPhoneNo { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string FarmerImage { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public Guid? UserGuid { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Another Model of the Tso User
public class TsoProfileModel
{
public long Tsoid { get; set; }
public string Tsoname { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string Tsoimage { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public TbDistrictCode DistrictCodeNavigation { get; set; }
public TbTehsilCode TehsilCodeNavigation { get; set; }
}
This is my ViewModel in which i am trying to incorporrate my data of Farmer/Tso
public class UserProfileInfo
{
public long? UserId { get; set; }
public string UserName { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public string image { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public string FatherHusbandName { get; set; }
public string CellPhone { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public string Role { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Below is the code I am trying to use.
if (User=="farmer")
{
var tbFarmerInfo = await
_farmerService.GetFarmerByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbFarmerInfo);
result.UserId = tbFarmerInfo.FarmerId;
result.UserName = tbFarmerInfo.FarmerName;
result.image = tbFarmerInfo.FarmerImage;
result.Role = "Farmer";
response.Data = result;
return response;
}
else if (User == "TSO")
{
string cellno = User.Claims.FirstOrDefault(c => c.Type ==
ClaimTypes.Name).Value.TrimStart('0');
var tbTsoInfo = await _tsoService.GetTSOByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbTsoInfo);
result.UserId = tbTsoInfo.Tsoid;
result.UserName = tbTsoInfo.Tsoname;
result.image = tbTsoInfo.Tsoimage;
result.Role = "TSO";
response.Data = result;
return response;
}
The expected result should be that both models can be mapped in the viewModel.
Like, if I map the FarmerProfile it should be mapped and if I want to map TsoProfile it should be mapped too.

Creating Types in Elasticsearch with NEST

So I a built a very basic Elastic example using just one Type (Products) I was able to use automap to build this and all worked well, now I want to expand on this and add more types I am running into issues but without any real exceptions being thrown to give me a clue as to what is going wrong.
class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string ProductCode { get; set; }
public string Barcode { get; set; }
public Nullable<int> ProductCategoryId { get; set; }
public int Length { get; set; }
public int Height { get; set; }
public int ProductTypeId { get; set; }
public string Url { get; set; }
public Nullable<int> ProductBrandId { get; set; }
public int Width { get; set; }
public string Html { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public decimal CostPrice { get; set; }
public Nullable<int> ProductBuyingPriceId { get; set; }
public int DispatchTimeInDays { get; set; }
public int LeadTimeInDays { get; set; }
public string ManufacturerPartNumber { get; set; }
public string Notes { get; set; }
public int StockAvailable { get; set; }
public decimal WeightKg { get; set; }
public Nullable<int> SellingPriceGroupId { get; set; }
public Nullable<decimal> ReviewRating { get; set; }
public int ReviewRatingCount { get; set; }
public bool NonReturnable { get; set; }
public bool LimitedStock { get; set; }
public Nullable<int> TaxRateId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
class ProductCategory
{
public int ProductCategoryId { get; set; }
public string Name { get; set; }
public Nullable<int> ParentProductCategoryId { get; set; }
public string FullPath { get; set; }
public string Code { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
var des = new CreateIndexDescriptor("myindex")
.Mappings(ms => ms
.Map<Product>(m => m.AutoMap())
.Map<ProductCategory>(m => m.AutoMap())
);
var res = elasticClient.CreateIndex(des);
Output.AppendText(res.ToString());
Output.AppendText(Environment.NewLine);
Output.AppendText("Index Created");
Output.AppendText(Environment.NewLine);
}
As mentioned if I just Include it works fine if I add Product Category nothing happens. TIA
Thanks for the responses As Russ said I was trying to have multiple types which wouldn't work

What would be the linq for this SQL Group Join

I use to work in SQL Server ,Having issue in converting same in Linq .
Its a Group Join in Linq.
SQL Query :
Select
Convert(varchar,CreateOn,101),
count(*),
Note as Total
from TrnExpense
group by Convert(varchar,CreateOn,101),Note
order by Convert(varchar,CreateOn,101) desc
My Output in SQL server follows :
Output in linq is also accepted same .Any help will be appreciated .
Class Generated for TrnExpense follows :
public partial class TrnExpense
{
public int id { get; set; }
public Nullable<int> TripId { get; set; }
public Nullable<int> TruckId { get; set; }
public Nullable<int> TrailerId { get; set; }
public Nullable<int> DriverId { get; set; }
public Nullable<int> ReferType { get; set; }
public Nullable<int> VendorId { get; set; }
public Nullable<int> ExpenseType { get; set; }
public Nullable<int> CountryId { get; set; }
public Nullable<int> StateId { get; set; }
public Nullable<int> CityId { get; set; }
public Nullable<double> Qty { get; set; }
public Nullable<int> qbStatus { get; set; }
public Nullable<int> qbTaxCode { get; set; }
public string QtyUnit { get; set; }
public Nullable<decimal> Rate { get; set; }
public Nullable<decimal> PreTaxAmt { get; set; }
public Nullable<decimal> Outstanding { get; set; }
public string InvoiceNo { get; set; }
public Nullable<double> ServiceFee { get; set; }
public Nullable<decimal> HstTax { get; set; }
public Nullable<double> TaxOne { get; set; }
public Nullable<double> TaxTwo { get; set; }
public string Currency { get; set; }
public string CardNo { get; set; }
public string UnitNo { get; set; }
public Nullable<int> PaymentId { get; set; }
public Nullable<int> SettlementId { get; set; }
public Nullable<int> VendorPayId { get; set; }
public string Note { get; set; }
public Nullable<System.DateTime> ExpenseDate { get; set; }
public Nullable<System.DateTime> DueDate { get; set; }
public string OwnerDeductionYN { get; set; }
public Nullable<int> Status { get; set; }
public Nullable<int> PayStatus { get; set; }
public Nullable<int> DriverDedStatus { get; set; }
public Nullable<int> DriverSettleId { get; set; }
public Nullable<int> UpdateBy { get; set; }
public Nullable<System.DateTime> LastUpdate { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public Nullable<int> CompanyId { get; set; }
public Nullable<decimal> AmountPaid { get; set; }
public Nullable<int> ExpPaymentType { get; set; }
public Nullable<bool> IsExcludeTax { get; set; }
public Nullable<double> Discount { get; set; }
public Nullable<System.DateTime> TransferToQBDate { get; set; }
public string CurrencyCode { get; set; }
public Nullable<int> DocumentUploadId { get; set; }
public string DeductionTypeFlag { get; set; }
public Nullable<decimal> NetAmount { get; set; }
public bool IsActive { get; set; }
public Nullable<System.DateTime> CreateOn { get; set; }
public string CreateBy { get; set; }
public Nullable<System.DateTime> ModifyOn { get; set; }
public string ModifyBy { get; set; }
public Nullable<decimal> Rate1Per { get; set; }
public Nullable<decimal> Rate2Per { get; set; }
public Nullable<bool> TaxIncluded { get; set; }
public Nullable<bool> TaxOnly { get; set; }
public Nullable<bool> IncludeTax1 { get; set; }
public Nullable<bool> IncludeTax2 { get; set; }
public string Source { get; set; }
public Nullable<int> SourceId { get; set; }
public string QbId { get; set; }
public Nullable<System.DateTime> QbLastSyncDate { get; set; }
public virtual CityState CityState { get; set; }
public virtual Country Country { get; set; }
public virtual Driver Driver { get; set; }
public virtual ExpenseType ExpenseType1 { get; set; }
public virtual StateCountry StateCountry { get; set; }
public virtual Vehicle Vehicle { get; set; }
public virtual Vehicle Vehicle1 { get; set; }
public virtual Vendor Vendor { get; set; }
}
var result = (from t in TrnExpense
group t by new { t.CreatedOn.Date, t.Note } into g
orderby g.Key.Date descending
select new{
CreatedOn = g.Key.Date,
Note = g.Key.Note,
Count = g.Count()
}).ToList();
Please try following code ,Written in lambda expression:
var resultSet=TrnExpenses.GroupBy(s=>new
{
s.CreateOn.Value.Date, s.Note
})
.OrderByDescending(s=>s.Key.Date)
.Select(s=>new
{
s.Key.Date,
s.Key.Note,
Count = s.Count()
});
I just tried and found the following and simply want to add on :
To access the date From datetime Column.Value.Date is used .
Following code will clear the same .
(from t in TrnExpenses
group t by new { t.CreateOn.Value.Date, t.Note } into g
orderby g.Key.Date descending
select new{
CreatedOn = g.Key.Date,
Note = g.Key.Note,
Count = g.Count()
}).ToList()

Convert in ObservableCollection (C# uwp)

I am writing an app for UWP.
I tried to use data binding according to this answer link.
Here are my classes:
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string order_key { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int customer_id { get; set; }
public double discount_total { get; set; }
public double discount_tax { get; set; }
public double shipping_total { get; set; }
public double shipping_tax { get; set; }
public double cart_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public string date_completed { get; set; }
public string date_paid { get; set; }
public string cart_hash { get; set; }
public List<object> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<object> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
}
public ObservableCollection<RootObject> Orders { get; set; }
Here is the code:
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
foreach (RootObject root in rootObjectData)
{
string date = root.date_created;
string name = root.billing.first_name + root.billing.last_name ;
Orders = new ObservableCollection<RootObject> { new RootObject { date_created = date,billing = name } };
}
With billing = name I have this error: Cannot implicitly convert type 'string' to 'Milano.InWork.Billing'
How can I fix this error?
Maybe this is simple, but I don't find a solution.
Thanks for the help!!
With billing = name I have this error: Cannot implicitly convert type 'string' to 'Milano.InWork.Billing'
Of course this error will occur, your billing in the class RootObject has the data type Billing, which is another class you defined.
Just from your code I think you only want to show the first_name and last_name as string in your root.billing, then you can change the code public Billing billing { get; set; } in your RootObject class to public string billing { get; set; }.

Categories