I have 2 classes .
first class is
public class Client : BaseEntity
{
public Client()
{
ReportingPeriods = new List<ReportingPeriod>();
UserAccesses = new List<UserClientAccess>();
GraphColours = new List<GraphColour>();
RangeColours = new List<RangeColour>();
Properties = new List<PropertyMaster>();
PropertyCustomFilterHeaderMasters = new List<PropertyCustomFilterHeaderMaster>();
InterestCustomFilterHeaderMasters = new List<InterestCustomFilterHeaderMaster>();
Comments = new List<Comment>();
CustomDashboards = new List<CustomDashboard>();
Bookmarks = new List<Bookmark>();
}
public string Name { get; set; }
[IgnoreComparing]
public byte[] Logo { get; set; }
[Display(Name = "Logo Name")]
public string LogoName { get; set; }
public ClientStatus Status { get; set; }
[IgnoreComparing]
public virtual ICollection<ReportingPeriod> ReportingPeriods { get; set; }
[IgnoreComparing]
public virtual ICollection<UserClientAccess> UserAccesses { get; set; }
public virtual ICollection<PropertyCustomFilterHeaderMaster> PropertyCustomFilterHeaderMasters { get; set; }
[IgnoreComparing]
public virtual ICollection<InterestCustomFilterHeaderMaster> InterestCustomFilterHeaderMasters { get; set; }
[IgnoreComparing]
public virtual ICollection<Comment> Comments { get; set; }
}
and the second class is clientDto
public class ClientDto : IdModel
{
public string Name { get; set; }
public string AreaUnit { get; set; }
public string Currency { get; set; }
}
Can i map this two classes with automapper with this way
cfg.CreateMap<Client, ClientDto>();
I'm trying to create mapping, everything works fine but app throws exception
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
Here is the linq query
public async Task<PagedResultOutput<ClientDto>> GetClients(GetClientsInput input)
{
var clients = Queryable().AsNoTracking();
var totalCount = await clients.CountAsync();
clients = clients.OrderBy(input.Sorting)
.Skip(input.SkipCount)
.Take(input.MaxResultCount);
return new PagedResultOutput<ClientDto>(totalCount, await clients.ProjectToListAsync<ClientDto>(_mapperConfiguration));
}
Related
As I said in the title, I'm trying to convert in the get method a model object to its DTO.
My method is to get users and is the next piece of code:
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<UserDTO>>> GetUsers()
{
var users = _context.Users.ToList();
var userDtos = new List<UserDTO>();
foreach (var user in users)
{
userDtos.Add(new UserDTO
{
IdUser = user.UserProfessionId,
UserName = user.UserName,
UserCompany = user.UserCompany,
UserMail = user.UserMail,
UserProfession = user.UserProfession,
UserProfessionField = user.UserProfessionField
});
}
return userDtos;
}
These are my model and DTO for user:
namespace Sims.Models
{
public partial class User
{
public User()
{
DataUsages = new HashSet<DataUsage>();
}
public long IdUser { get; set; }
public int UserProfessionId { get; set; }
public int UserProfessionFieldId { get; set; }
public string? UserName { get; set; }
public string? UserMail { get; set; }
public string? UserCompany { get; set; }
public byte[]? UserPicture { get; set; }
public virtual Profession UserProfession { get; set; } = null!;
public virtual ProfessionField UserProfessionField { get; set; } = null!;
public virtual ICollection<DataUsage> DataUsages { get; set; }
}
}
and
namespace sims.DTO
{
public partial class UserDTO
{
public long IdUser { get; set; }
public string? UserName { get; set; }
public string? UserMail { get; set; }
public string? UserCompany { get; set; }
public virtual ProfessionDTO UserProfession { get; set; } = null!;
public virtual ProfessionFieldDTO UserProfessionField { get; set; } = null!;
}
}
Profession and ProfessionField are also models and have their own DTO. But in the get method, the two following lines contain the same error as it "cannot implicitly convert type '....Models.Profession' to '....DTO.ProfessionDTO'".
Do you have any idea ?
In case, here is an example of the Profession Model and DTO:
namespace Sims.Models
{
public partial class Profession
{
public Profession()
{
ProfessionFields = new HashSet<ProfessionField>();
Users = new HashSet<User>();
}
public int IdProfession { get; set; }
public string ProfessionName { get; set; } = null!;
public virtual ICollection<ProfessionField> ProfessionFields { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
and
namespace sims.DTO
{
public class ProfessionDTO
{
public int IdProfession { get; set; }
public string ProfessionName { get; set; } = null!;
}
}
Thanks for reading
The UserProfession property is of type ProfessionDTO:
public virtual ProfessionDTO UserProfession { get; set; } = null!;
But you're trying to populate it with an object of type Profession:
UserProfession = user.UserProfession,
Just as the error states, they are different types and can't be substituted for one another. Populate the property with an instance of ProfessionDTO instead:
UserProfession = new UserProfessionDTO
{
IdProfession = user.UserProfession.IdProfession,
ProfessionName = user.UserProfession.ProfessionName
},
If the user.UserProfession field is null then you'd need to check for that. For example:
UserProfession = user.UserProfession == null ?
null as UserProfessionDTO :
new UserProfessionDTO
{
IdProfession = user.UserProfession?.IdProfession,
ProfessionName = user.UserProfession?.ProfessionName
},
I have two classes that are similar. I'm trying to see if I can simply use one. The first is in our DataModel assembly, and used in our DbContext.
public partial class type210_MotorCarrierFreightInvoice
{
public int MotorCarrierFreightInvoiceId { get; set; } // MotorCarrierFreightInvoiceId (Primary key)
public string InvoiceId { get; set; } // InvoiceId
public DateTime BillDate { get; set; } // BillDate
public string TrackingNumber { get; set; } // TrackingNumber
public decimal NetShipmentCharge { get; set; } // NetShipmentCharge
public long InterchangeTransactionDetailId { get; set; } // InterchangeTransactionDetailId
public long? BillToAddressId { get; set; } // BillToAddressId
public long? ConsigneeAddressId { get; set; } // ConsigneeAddressId
public long? ShipperAddressId { get; set; } // ShipperAddressId
// Foreign keys
public virtual interchange_TransactionDetail interchange_TransactionDetail { get; set; } // fk_Type210_MotorCarrierFreightInvoice_Interchange_TransactionDetail
public virtual typeAny_Address typeAny_Address_BillToAddressId { get; set; }
public virtual typeAny_Address typeAny_Address_ConsigneeAddressId { get; set; }
public virtual typeAny_Address typeAny_Address_ShipperAddressId { get; set; }
public type210_MotorCarrierFreightInvoice()
{
InitializePartial();
}
partial void InitializePartial();
}
The second class should represent the same object.
public class Type210MotorCarrierFreightInvoice
{
public int MotorCarrierFreightInvoiceId { get; set; }
public string InvoiceId { get; set; }
public DateTime BillDate { get; set; }
public string TrackingNumber { get; set; }
public decimal NetShipmentCharge { get; set; }
public long InterchangeTransactionDetailId { get; set; }
public Address BillToAddress { get; set; }
public Address ConsigneeAddress { get; set; }
public Address ShipperAddress { get; set; }
}
I'm working with a WebApi service that will expose the data via JSON. Basically what I'm trying is this:
[Route("api/Subscriber/Get210sNew/{transactionId}")]
[Route("api/Subscriber/Get210sNew/{transactionId}/{limit}")]
public IEnumerable<type210_MotorCarrierFreightInvoice> Get210sDOES_NOT_WORK(int transactionId, int limit = DefaultLimit)
{
var key = new QueryAfterId(transactionId, limit);
var dataService = new Type210DataService(_ediContext);
return dataService
.Get(key)
.Select(x => x);
}
[Route("api/Subscriber/Get210s/{transactionId}")]
[Route("api/Subscriber/Get210s/{transactionId}/{limit}")]
public IEnumerable<type210_MotorCarrierFreightInvoice> Get210sWorks(int transactionId, int limit = DefaultLimit)
{
var key = new QueryAfterId(transactionId, limit);
var dataService = new Type210DataService(_ediContext);
return dataService
.Get(key)
.Select(Map);
}
Here is the Map method:
private static Type210MotorCarrierFreightInvoice Map(
type210_MotorCarrierFreightInvoice dbNotice)
{
return new Type210MotorCarrierFreightInvoice
{
MotorCarrierFreightInvoiceId = dbNotice.MotorCarrierFreightInvoiceId,
InvoiceId = dbNotice.InvoiceId,
BillDate = dbNotice.BillDate,
ShipDate = dbNotice.ShipDate,
TrackingNumber = dbNotice.TrackingNumber,
PurchaseOrderNumber = dbNotice.PurchaseOrderNumber,
BillOfLading = dbNotice.BillOfLading,
NetShipmentCharge = dbNotice.NetShipmentCharge,
InterchangeTransactionDetailId = dbNotice.InterchangeTransactionDetailId,
BillToAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_BillToAddressId),
ConsigneeAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_ConsigneeAddressId),
ShipperAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_ShipperAddressId)
};
}
Get210sWorks will return Json data to the browser. Get210sDOES_NOT_WORK does not. Both queries get the same number of records. But Get210sDOES_NOT_WORK shows no records in the browser window.
Why can't I return an IEnumerable of my DataModel class as Json?
I grabbed the latest NuGet of NEST and tried to implement simple elastic search. My code do not index an object. IsValid returns false but I have no idea why. Result is also empty.
Here is my snippet of code. I'll be grateful for the help.
public ActionResult Search()
{
var node = new Uri("http://localhost:49997");
var settings = new ConnectionSettings(
node,
defaultIndex: "my-application"
);
var client = new ElasticClient(settings);
var uporabnik = new uporabnik
{
idUporabnik = 99,
ime = "John",
priimek = "Schwarz"
};
var index = client.Index(uporabnik);
if (!index.IsValid)
{
Log.Error("Error when indexing.");
}
var results = client.Search<uporabnik>(s => s.Query(q => q.Term(p => p.priimek, "Novak")));
return View();
}
I tried Console.WriteLine(index.ServerError.Error), but there comes an error: Object reference not set to an instance of an object. So I do not know, what is error message.
Class uporabnik is below.
public partial class uporabnik
{
public uporabnik()
{
this.ocena = new HashSet<ocena>();
this.predmet = new HashSet<predmet>();
this.studentpredmet = new HashSet<studentpredmet>();
}
[Required]
public int idUporabnik { get; set; }
public Nullable<int> vpisnaStevilka { get; set; }
[Required]
[RegularExpression(#"^[A-z]*$"]
public string ime { get; set; }
[Required]
[RegularExpression(#"^[A-z]*$"]
public string priimek { get; set; }
[RegularExpression(#"^[\w\d-\.]+#([\w\d-]+\.)+[\w-]{2,4}$"]
public string email { get; set; }
public string geslo { get; set; }
[Required]
public string mobi { get; set; }
[Required]
[RegularExpression(#"^[MZ]*$"]
public string spol { get; set; }
[RegularExpression(#"^[123]{1}$"]
public Nullable<int> letnikStudija { get; set; }
public System.DateTime datumRegistracije { get; set; }
public System.DateTime zadnjiDostop { get; set; }
public int idVloge { get; set; }
[JsonIgnore]
public virtual ICollection<ocena> ocena { get; set; }
[JsonIgnore]
public virtual ICollection<predmet> predmet { get; set; }
[JsonIgnore]
public virtual ICollection<studentpredmet> studentpredmet { get; set; }
[JsonIgnore]
public virtual vloga vloga { get; set; }
}
I am trying to grasp EF Code First but I still do not get how to access the referenced objects from another class (due to lack of enough knowledge, I cannot even formulate the question).
Here's what my simple code looks like:
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class BreakAwayContext: DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using(var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
private static void InsertLodging()
{
var lodging = new Lodging()
{
Name = "x",
IsResort = false,
Owner = "asdasd"
};
using(var context = new BreakAwayContext())
{
var dest = context.Destinations.Find(1);
lodging.Destination = dest;
context.Lodgings.Add(lodging);
context.SaveChanges();
}
}
private static void ShowLodgings()
{
using(var context = new BreakAwayContext())
{
foreach(var l in context.Lodgings)
{
Console.WriteLine("{0} {1} {2}", l.Name, l.Owner, l.Destination.Name);
}
}
}
I get a NullReferenceException on the line I try to write the destination name to the console.
Thanks in advance.
Try using navigation properties:
First make Destination virtual
public virtual Destination Destination { get; set; }
Then use Include method
foreach(var l in context.Lodgings.Include(x => x.Destination))
Just set Destination property in your Lodging class, virtual. This tell, the EF to load Destination automatically when you need it(Lazy Loading).
So your Lodging class should looks like:
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public virtual Destination Destination { get; set; }
}
I am trying to AutoMapper to EF models which are nested inside nested.
For Example in below code categorySrc, languageSrc, abstractSrc..etc and categoryDest, languageDest, abstractDest ..etc classes are same.
Now I am trying to Map categorySrc to categoryDest, So I made like below, if throwing an error
Is something I am doing wrong here?
var categoryData = abstractContext.GetCategoryByCatId(catId);
Mapper.CreateMap<Models.categoryDest, categorySource>();
Mapper.CreateMap<languageDest, Models.languageSource>();
Mapper.CreateMap<#abstractDest, Models.#abstractSrc>();
Mapper.CreateMap<abstract_categoryDest, Models.abstract_categorySrc>();
Mapper.CreateMap<questionDest, Models.questionSrc>();
Mapper.CreateMap ... //For other objects
Mapper.CreateMap ...//For other objects
Mapper.AssertConfigurationIsValid(); //Error occurring here
var category = Mapper.Map<category,Models.category>(categoryData);
Classes:
public partial class categoryDest
{
public int category_id { get; set; }
public int language_id { get; set; }
public virtual languageDest language { get; set; }
}
public partial class languageDest
{
public language()
{
this.abstracts = new HashSet<#abstractDest>();
this.abstract_category = new HashSet<abstract_categoryDest>();
this.categories = new HashSet<categoryDest>();
this.questions = new HashSet<questionDest>();
}
public int language_id { get; set; }
public string language_name { get; set; }
public string language_locale_code { get; set; }
public virtual ICollection<#abstractDest> abstracts { get; set; }
public virtual ICollection<abstract_categoryDest> abstract_category { get; set; }
public virtual ICollection<categoryDest> categories { get; set; }
public virtual ICollection<questionDest> questions { get; set; }
}
public partial class #abstractDest
{
public #abstract()
{
this.abstract_category = new HashSet<abstract_categoryDest>();
this.abstract_fields = new HashSet<abstract_fieldsDest>();
this.abstract_image = new HashSet<abstract_imageDest>();
this.people = new HashSet<person>();
}
public int abstract_id { get; set; }
public int language_id { get; set; }
public string abstract_name { get; set; }
public virtual ICollection<abstract_categoryDest> abstract_category { get; set; }
public virtual ICollection<abstract_fieldsDest> abstract_fields { get; set; }
public virtual ICollection<abstract_imageDest> abstract_image { get; set; }
public virtual languageDest language { get; set; }
public virtual ICollection<personDest> people { get; set; }
}
How to do this complex mapping?