Recently I've experienced this error while trying to update entities in MS SQL Database.
I have two models:
[AutoMap(typeof(Employees))]
[Table("Employees")]
public class Employees : FullAuditedEntity
{
public Employees()
{
EmployeesAdresses = new HashSet<EmployeesAdresses>();
WorkTimeEntries = new HashSet<WorkTimeEntries>();
ContractEntries = new HashSet<ContractEntries>();
}
public string Name { get; set; }
public string Surname { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
public ICollection<EmployeesAdresses> EmployeesAdresses { get; set; }
public ICollection<WorkTimeEntries> WorkTimeEntries { get; set; }
public ICollection<ContractEntries> ContractEntries { get; set; }
[NotMapped]
public List<GroupRelations> GroupRelations { get; set; }
}
[AutoMap(typeof(EmployeesAdresses))]
[Table("EmployeesAdresses")]
public class EmployeesAdresses : FullAuditedEntity
{
public string Street { get; set; }
public string HouseNumber { get; set; }
public string ApartmentNumber { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public bool IsDefault { get; set; }
public bool IsActive { get; set; }
[ForeignKey("Employees")]
public int EmployeeId { get; set; }
public virtual Employees Employee { get; set; }
}
I am trying to update Employee Adress using simple appservice:
public async Task UpdateEmployee (Employees employeeInput)
{
try
{
var _employee = await _employeesRepository.GetAllIncluding(x => x.EmployeesAdresses).Where(x => x.Id == employeeInput.Id).SingleOrDefaultAsync();
if (_employee == null)
throw new Exception($"Brak pracownika o ID: {employeeInput.Id}");
_employee.EmployeesAdresses.Clear();
_employee.WorkTimeEntries.Clear();
ObjectMapper.Map(employeeInput, _employee);
await _employeesRepository.UpdateAsync(_employee);
}
catch (Exception ex)
{
throw new UserFriendlyException(#"Wystąpił błąd podczas aktualizacji pracownika.", ex.Message, ex.InnerException);
}
}
I am getting StackOverFlowException and I really don't know whats the issue. Last error on stacktrace in diagnostic tool event tab is StringCompare error.
Did you experience such a behaviour? Any ideas what might be a problem?
Related
Hi i need to get all data from db. I try with dapper QueryMultipleAsync and also with QueryAsync but in first case get some of the data and than breaks and in second the result for each entity is null. When i execute the Sql query in MS SQL everything works fine.
My Entities:
public class InfozasitePcja
{
public string ComputerName { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Biosserial { get; set; }
public string SystemEnclosureserial { get; set; }
public string Manufacturer { get; set; }
public string model { get; set; }
public string OS { get; set; }
public string Site { get; set; }
public int TotalMemory { get; set; }
public int HardriveSize { get; set; }
public int FreeSpace { get; set; }
public int MaxCPUSpeed { get; set; }
public string CPUModel { get; set; }
public int ID64BitCompatible { get; set; }
}
public class SEPreport
{
public string COMPUTER_NAME { get; set; }
public string PROCESSOR_TYPE { get; set; }
public string PROCESSOR_CLOCK { get; set; }
public string PROCESSOR_NUM { get; set; }
public string MEMORY { get; set; }
public string BIOS_VERSION { get; set; }
public string OPERATION_SYSTEM { get; set; }
public string SERVICE_PACK { get; set; }
public string CURRENT_LOGIN_USER { get; set; }
public string MAC_ADDR1 { get; set; }
public string IP_ADDR1 { get; set; }
public string DISK_TOTAL { get; set; }
public string BIOS_SERIALNUMBER { get; set; }
public string AGENT_VERSION { get; set; }
public string STATUS { get; set; }
public string LAST_UPDATE_TIME { get; set; }
}
public class Users
{
public string displayname { get; set; }
public string SumAccountName { get; set; }
public float EmployeeNumber { get; set; }
public DateTime whenCreated { get; set; }
public string distinquishedName { get; set; }
public string Company { get; set; }
public int OfficePhone { get; set; }
public string mail { get; set; }
public string distinguishedname { get; set; }
public DateTime LastLogonDate { get; set; }
}
public class Eerv
{
public string Ime { get; set; }
public string Prezime { get; set; }
[Column("F.br.")]
public string Fabricki { get; set; }
[Column("T.Mesto")]
public string Troskovno { get; set; }
[Column("Ime T.Mesto")]
public string ImeTroskovno { get; set; }
}
I have also one summary entity for all.
public partial class GetInfoForUserSummary
{
public IEnumerable<InfozasitePcja> Info { get; set; }
public IEnumerable<SEPreport> SEP { get; set; }
public IEnumerable<Users> Users{ get; set; }
public IEnumerable<Eerv> Eerv { get; set; }
}
The QueryMultipleAsync code:
public async Task<GetInfoForUserSummary> GetInfoForUser(string column, string search)
{
GetInfoForUserSummary result = new GetInfoForUserSummary();
try
{
var query = #"Select * From InfoZaSitePCja inner join SEPreport ON InfoZaSitePCja.[Computer Name] = SEPreport.COMPUTER_NAME
Inner JOIN Users ON SEPreport.CURRENT_LOGIN_USER = Users.SamAccountName Inner join [Test].[dbo].[Zoki]
ON Users.EmployeeNumber = [Test].[dbo].[Zoki].[F.br.] Where [" + column + "] LIKE '%" + search + "%'";
var res = await Connection.QueryMultipleAsync(query, commandType: CommandType.Text, transaction: Transaction);
result.Info = await res.ReadAsync<InfozasitePcja>();
result.SEP = await res.ReadAsync<SEPreport>();
result.Users = await res.ReadAsync<Users>();
result.Eerv = await res.ReadAsync<Eerv>();
}
catch (Exception e)
{
_logger.Error(e);
throw new Exception("Database Error", e);
}
return result;
}
The QueryAsync Code:
public async Task<IEnumerable<InfozasitePcja>> GetInfoForUser(string column, string search)
{
try
{
var query = #"Select * From InfoZaSitePCja inner join SEPreport ON InfoZaSitePCja.[Computer Name] = SEPreport.COMPUTER_NAME
Inner JOIN Users ON SEPreport.CURRENT_LOGIN_USER = Users.SamAccountName Inner join [Test].[dbo].[Zoki]
ON Users.EmployeeNumber = [Test].[dbo].[Zoki].[F.br.] Where [" + column + "] LIKE '%" + search + "%'";
var param = new DynamicParameters();
var list = await Connection.QueryAsync<InfozasitePcja>(query, commandType: CommandType.Text, transaction: Transaction);
return list;
}
catch (Exception e)
{
_logger.Error(e);
throw new Exception("Database Error", e);
}
}
I'm working on an web API, where it needs to receive the multi-part form data with in a model. As of now it's not receiving the request and showing the Bad request When I tried from the Postman.
My model :
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
In the above class/model "invoice_file" and "other_files" can have multiple file uploads so I made it List.
My Action Method :
[HttpPost]
[Route("CreateInvoice")]
public IActionResult CreateInvoice([FromForm]InvoiceDetails idobj )
{
//var modelData = Request.Form["invoice_file"];
Response resobj = new Response();
try
{
if (idobj.invoice_file.Count > 0)
{
resobj = _dataContext.AddInvoice(idobj);
if (resobj.flag == true)
{
Upload(idobj);
}
}
else
{
resobj.flag = false;
resobj.message = "please upload atleast one invioce file";
}
}
catch (Exception ex)
{
}
return Ok(resobj);
}
How can I make the action method or model, in such a way that user can upload the model with multiple files to the properties other_files & invoice_file.
Reference of postman Image
As CodeCaster says,add Content-Type:multipart/form-data; and change List<IFormCollection> to List<IFormFile>.It is not changing the whole model to List.So you can also retrieve other information which exists in your model with idobj.xxx.Change
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
to
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormFile> invoice_file { get; set; }
[FromForm(Name = "other_files")]
public List<IFormFile> other_files { get; set; }
}
result:
IFormCollection is used to retrieve all the values from posted form data.refer to the official document.
If you want to use c,you can try to use it,you can do like this
public IActionResult CreateInvoice([FromForm]IFormCollection idobj)
and you need to get the data you want to foreach keys of IFormCollection,so public List<IFormCollection> invoice_file { get;set;} is better than use IFormCollection.
I am trying to insert JSON data into my models via EF 6. I am getting this error;
Inner Exception is {0}System.ArgumentException: Could not cast or convert from System.String to EPINMiddleWareAPI.Models.Serial.
konum: Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
konum: Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
konum: Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
Message ---
{0}Error converting value "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7" to type 'EPINMiddleWareAPI.Models.Serial'. Path 'coupons[0].serials[0]', line 1, position 310.
Here is my model structure:
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<Serial> serials { get; set; }
public List<Pin> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
}
public class Serial
{
public int Id { get; set; }
public string serials { get; set; }
public int CouponID { get; set; }
public virtual Coupon coupons { get; set; }
}
My sample JSON:
"{\"referenceId\":\"0000000046\",\"paymentId\":\"MDO1037624\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"currency\":\"TL\",\"unitPrice\":\"46,47\",\"totalPrice\":\"46,47\",\"merchantProductCode\":\"\",\"purchaseStatusCode\":\"00\",\"purchaseStatusDate\":\"2019-03-17T20:58:48Z\",\"coupons\":[{\"serials\":[\"c57a55b5-b2d4-46e7-86e0-cc13726ca8a7\"],\"pins\":[\"T6VC-XC6X-3H6JS-NVWL-93PCa\"]}],\"version\":\"V1\",\"signature\":\"2f961c7dbc32c3bc128b6e69d19e8e1a\",\"applicationCode\":\"52e7cf966b724749a7c4efadc3727ed7\"}"
How can I fix this problem? I would like to insert this JSON into my database tables. I am using EF 6.
edit:
This model structure solved my problem. Now I can insert serials and pins into database.
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<string> serials { get; set; }
public List<string> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
public List<string> StringsSerial
{
get { return serials; }
set { serials = value; }
}
public List<string> StringsPin
{
get { return pins; }
set { pins = value; }
}
[Required]
public string Serial
{
get { return String.Join(",", serials); }
set { serials = value.Split(',').ToList(); }
}
[Required]
public string Pin
{
get { return String.Join(",", pins); }
set { pins = value.Split(',').ToList(); }
}
}
Thanks in advance.
you're json is wrong
take a look into the coupons array, you initialize the serials array with an string/guid and not with a model of serial
it should be
"coupons": [{
{
"serials": [{
"serials": "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7"
}
],
}
}
]...
I guess for Pins the same
how do I query this many to many relationship? I am starting with ACCOUNT, and want to return the ExecutingBroker.Firm associated with it.
I am starting with Account, then I guess drill to MANAGER, then to MAPPING_MANAGER, then to EXECUTINGBROKER.
Here is my query so far...
var student = dbEF.Accounts
.Where(x => x.AccountNumber == acctNum)
.Select(x => new DTOCrmDetails()
{
AccountNumber = x.AccountNumber,
AccountName = x.AccountName,
DateOpened = x.DateOpened,
CommissionId = x.CommissionId,
Commission = x.Commission,
ManagerID = x.ManagerID,
ManagerName = x.Manager.ManagerName,
Manager = x.Manager,
Employees = x.Manager.Employees,
WireInstructionsUSD = x.Manager.WireInstructionsUSDs
}).FirstOrDefault();
below is the code that was generated from ef from existing database.
public partial class Manager
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Manager()
{
this.Accounts = new HashSet<Account>();
this.Employees = new HashSet<Employee>();
this.WireInstructionsUSDs = new HashSet<WireInstructionsUSD>();
this.Mapping_ManagersExecutingBrokers = new HashSet<Mapping_ManagersExecutingBrokers>();
}
public int ManagerID { get; set; }
public string ManagerName { get; set; }
public string Strategy { get; set; }
public string ManagerShortCode { get; set; }
public Nullable<int> WireInstructionsUsdID { get; set; }
public Nullable<int> WireInstructionsForeignID { get; set; }
public string MEtradingPlatform { get; set; }
public string EtradingCostResp { get; set; }
public string NotesManager { get; set; }
public bool MainStrategy { get; set; }
public string PathPayments { get; set; }
public string PathEtrading { get; set; }
public string LEI { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Account> Accounts { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employee> Employees { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WireInstructionsUSD> WireInstructionsUSDs { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Mapping_ManagersExecutingBrokers> Mapping_ManagersExecutingBrokers { get; set; }
}
}
{
using System;
using System.Collections.Generic;
public partial class Mapping_ManagersExecutingBrokers
{
public int Mapping_ManagersExecutingBrokersId { get; set; }
public Nullable<int> ManagerID { get; set; }
public Nullable<int> ExecutingBrokersId { get; set; }
public virtual ExecutingBroker ExecutingBroker { get; set; }
public virtual Manager Manager { get; set; }
}
}
public partial class ExecutingBroker
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ExecutingBroker()
{
this.Mapping_ManagersExecutingBrokers = new HashSet<Mapping_ManagersExecutingBrokers>();
}
public int ExecutingBrokersId { get; set; }
public string Firm { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Mapping_ManagersExecutingBrokers> Mapping_ManagersExecutingBrokers { get; set; }
}
You have to go through Mapping_ManagersExecutingBrokers, since you've modelled it that way.
Keep in mind that you have a collection of Firms, since it's a many-to-many-relationship.
.Select(account => new { Firms = account.Manager.Mapping_ManagersExecutingBrokers
.Select(meb => meb.ExecutingBroker.Firm) });
I am use code first model with a relationship below
public class ApplicationUser : IdentityUser
{
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserSchool { get; set; }
public UserProfileData UserProfileData { get; set; }
public int? MedicalSpecialtyId { get; set; }
public virtual MedicalSpecialty MedicalSpecialty { get; set; }
// public int? AnalyticsDataId { get; set; }
// public ICollection<AnalyticsData> AnalyticsDatas { get; set; }
}
public class MedicalSpecialty
{
public int Id { get; set; }
public string Description { get; set; }
// public int ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public ICollection<ProgramDetailData> ProgramDetailDatas { get; set; }
}
And when I try to get a User's associated MedicalSpecialty object it is NULL
userSpecialtyName = currentUser.MedicalSpecialty.Description;
BUT when I run this code above it the currentUser.MedicalSpecialty is no longer NULL. What happened?? Somehow that LINQ query woke up the object and filled it with data
var userSpecialtyId = currentUser.MedicalSpecialtyId;
userSpecialtyName = _medicalSpecialtyRepository.Find
(x => x.Id == userSpecialtyId).FirstOrDefault().Description;
userSpecialtyName = currentUser.MedicalSpecialty.Description;