AutoMapper assign property from parent type property - asp.net-core

is there i way in autoMapper to assign child class property from parent class property. I have looked at other example out there but didn't quite get what I need so posting my issue here.
here's code
class ParentDB {
public int id;
public DateTime CreatedDate;
public string Name;
}
class ChildDB {
public int id;
publi string Name;
public int Number;
}
class ParentViewModel : IMapFrom <ParentDB> {
pulic int id;
pulic string Name;
public ChildViewModel child;
}
class ChildViewModel : IMapFrom <ChildDB> {
public int Id;
pulic string Name;
pulic DateTime ParentCreated;
}
public interface IMapFrom<T>
{
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
Problem is that "ParentCreated" time in ChildViewMode needs to come from ParentDB. I have tried following with no success
class ParentViewModel : IMapFrom <ParentDB> {
pulic int id;
pulic string Name;
public ChildViewModel child;
public DateTime CreatedDate;
public void Mapping(Profile profile)
{
profile.CreateMap<ParentDB, ParentViewModel>()
.AfterMap( (s,d) => d.ChildViewModel.ParentCreated = d.CreatedDate);
}
}
var children = await Context.ParentDB
.ProjectTo<ParentViewModel>(mapper.ConfigurationProvider)
.ToListAsync()
with above although ParentViewModel.CreatedDate has date, ChildViewModel.ParentCreated is null. can some please explain why its not assigning date in AfterMap and hwo can this be fix.
Thanks

I am not how to do the map in the way you shared, since I can't see the IMapFrom <T> interface.
Maybe you can try below:
var parent = new ParentDB { id = 1, Name = "AA", CreatedDate = DateTime.Now.AddDays(1) };
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ParentDB, ParentViewModel>()
.AfterMap((s, d) => d.ChildViewModel.ParentCreated = s.CreatedDate);
});
var mapper = configuration.CreateMapper();
ParentViewModel parentViewModel = mapper.Map<ParentViewModel>(parent);
Also you should initlize the ChildVewModel in the ParentViewModel, otherwise it will occur a NullReference exception
public class ParentViewModel
{
public ParentViewModel()
{
ChildViewModel = new ChildViewModel();
}
public int id;
public string Name;
public ChildViewModel ChildViewModel;
}
Result:

Related

Create blazor component based on InputBase with interface

I need to create a Blazor component inherited from the Microsoft.AspNetCore.Components.Forms.InputBase class that implements an interface.
My interface is realised with this code :
public interface Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
}
And my class who inherit of interface is
public class Child : Person
{
private Guid id;
private string name;
private string firstName;
public Guid Id { get => id; set => id = value; }
public string Name { get => name ; set => name = value; }
public string FirstName { get => firstName; set => firstName = value; }
public Child(string name, string firstname)
{
this.name = name;
this.firstName = firstname;
}
}
For my component this inherit of InputBase is declared with :
#inherits Microsoft.AspNetCore.Components.Forms.InputBase<Person?>
For use my component in blazor page, I have used the code below :
<MyTest #bind-Value="#child" />
When I generate my solution, I have an error :
Error CS1503 Argument 2: cannot convert from 'Microsoft.AspNetCore.Components.EventCallback<Test.Children>' to 'Microsoft.AspNetCore.Components.EventCallback'
Can you help me understand this mistake? Do I need to create a specific getter/setter to transform the Child into a Person or is there another solution?
Thanks for your help !
Vincent

#Indexed annotation is ignored

I have a simple Product class as it follows
#SolrDocument(collection = "product")
public class Product {
#Id
#Indexed(name = "id", type = "string")
private String id;
#Field
#Indexed(name = "namex", type = "text_general", stored = false, searchable=true)
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
my problem is that the annotation #Indexed is completely ignored. The name of the field is simply name (instead of namex) and the field is stored. Any guess?
UPDATE 1 if I remove the type annotation name works, but stored has no effect still
I managed by modifying the bean that creates the SolrTemplate object like follows:
#Bean
public SolrTemplate solrTemplate(SolrClient client) throws Exception {
SolrTemplate st = new SolrTemplate(client);
st.setSchemaCreationFeatures(Collections.singletonList(Feature.CREATE_MISSING_FIELDS));
st.afterPropertiesSet();
return st;
}

Room Android : Entities and Pojos must have a usable public constructor

Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type)
Am integrating room into my existing project. While annotating a POJO, which implements Parcelable, with #Entity tag and making necessary changes, am getting this error. I already have an empty constructor in it. Any help would be appreciated.
#Entity(tableName = "Departments")
public class Department implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String departmentName;
private String logoUrl;
#Embedded
private ArrayList<Template> templateList;
public Department() {
}
protected Department(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.departmentName = in.readString();
this.logoUrl = in.readString();
this.id = (Integer) in.readSerializable();
this.templateList = in.createTypedArrayList(Template.CREATOR);
}
public static final Creator<Department> CREATOR = new Creator<Department>() {
#Override
public Department createFromParcel(Parcel in) {
return new Department(in);
}
#Override
public Department[] newArray(int size) {
return new Department[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(departmentName);
dest.writeString(logoUrl);
dest.writeSerializable(id);
dest.writeTypedList(templateList);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public ArrayList<Template> getTemplateList() {
return templateList;
}
public void setTemplateList(ArrayList<Template> templateList) {
this.templateList = templateList;
}
}
#Entity(tableName = "Templates")
public class Template implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String code;
private String description;
private Integer departmentId;
#Embedded
private ArrayList<Issue> issueList;
public Template() {
}
private Template(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.code = in.readString();
this.description = in.readString();
this.id = (Integer) in.readSerializable();
this.departmentId = (Integer) in.readSerializable();
this.issueList = in.createTypedArrayList(Issue.CREATOR);
}
public static final Creator<Template> CREATOR = new Creator<Template>() {
#Override
public Template createFromParcel(Parcel in) {
return new Template(in);
}
#Override
public Template[] newArray(int size) {
return new Template[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(code);
dest.writeString(description);
dest.writeSerializable(id);
dest.writeSerializable(departmentId);
dest.writeTypedList(issueList);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Issue> getIssueList() {
return issueList;
}
public void setIssueList(ArrayList<Issue> issueList) {
this.issueList = issueList;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
}
#Entity(tableName = "Issues")
public class Issue implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String code;
private String description;
private Integer parentIssue;
public Issue() {
}
protected Issue(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.code = in.readString();
this.description = in.readString();
this.id = (Integer) in.readSerializable();
this.parentIssue = (Integer) in.readSerializable();
}
public static final Creator<Issue> CREATOR = new Creator<Issue>() {
#Override
public Issue createFromParcel(Parcel in) {
return new Issue(in);
}
#Override
public Issue[] newArray(int size) {
return new Issue[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(code);
dest.writeString(description);
dest.writeSerializable(id);
dest.writeSerializable(parentIssue);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getParentIssue() {
return parentIssue;
}
public void setParentIssue(Integer parentIssue) {
this.parentIssue = parentIssue;
}
}
Room assumes your entity class will be having only one constructor. But there is no such limitations, If you have multiple constructor then annotate one of them with
#Ignore
Room will ignore this constructor and compile without any error.
Example
#Entity(tableName = "Departments")
public class Department implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String departmentName;
private String logoUrl;
#Embedded
private ArrayList<Template> templateList;
/**Room will ignore this constructor
**/
#Ignore
public Department() {
}
protected Department(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.departmentName = in.readString();
this.logoUrl = in.readString();
this.id = (Integer) in.readSerializable();
this.templateList = in.createTypedArrayList(Template.CREATOR);
}
}
I'm not sure why you are getting your specific constructor error. That said your code will error from embedding the ArrayList. #Embedded is not meant to be used this way. #Embedded allows you to flatten your POJO structure when storing it. Nested POJO properties will appear as if they had been properties on the parent POJO. Using Embedded on a List is the same as asking it to flatten the properties of the ArrayList object and store them, not flatten the list items and store them.
The appropriate measure is to transition into a foreign key, primary key relationship. An alternative solution is to create a new POJO that contains your list of items (ie Templates, with an 's'). This would contain an ArrayList of Template objects. You would then define a converter that converts the POJO to a json/comma seperated list, and stores it in a single column that by default would be called "templates". Here is a link to this approach :
Android room persistent library - TypeConverter error of error: Cannot figure out how to save field to database"
Hope this helps.

JPA OneToMany bidirectional relation [EclipseLink-63] error

Please can you help me? In JPA, I try to create a OneToMany bidirectional relation, but I have the following errors :
"[EclipseLink-63] : The instance creation method [entity.OrderLine.], with no parameters, does not exist, or is not accessible.
[EclipseLink-28019] : Deployment of PersistenceUnit [simple-jpaPU] failed. Close all factories for this PersistenceUnit."
There are my entities :
OneToMany Entity :
package entity;
import java.util.*;
import java.io.Serializable;
import javax.persistence.*;
import org.eclipse.persistence.annotations.TimeOfDay;
#Entity
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#OneToMany(mappedBy = "o")
private List<OrderLine> orderLines;
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public List<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(ArrayList<OrderLine> orderLines) {
this.orderLines = orderLines;
}
public Order(Date creationDate) {
this.creationDate = creationDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "entity.Order[ id=" + id + " ]";
}
}
ManyToOne Entity :
package entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="orderline_table")
public class OrderLine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String item;
private Double unitPrice;
private Integer quantity;
#ManyToOne
Order o;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public OrderLine(String item, Double unitPrice, Integer quantity) {
this.item = item;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "entity.OrderLine[ id=" + id + " ]";
}
}
It fails because OrderLine does not have no-arg constructor. It is required as stated in JPA 2.1 specification (Chapter 2.1):
The entity class must have a no-arg constructor. The entity class may have other constructors as well.The no-arg constructor must be public or protected.
Default constructor is not generated because other constructor is given. Problem can be fixed by adding following constructor:
public OrderLine() {
}

Error reading annotations with composite key in EBean

Following this link
I would like to use OneToMany instead ManyToMany annotation, having middle class with composite key in it using Ebean. I have this error:
java.lang.RuntimeException: Error reading annotations for models.SoftwareTagPk
This is my SoftwareTagPk class:
#Embeddable
public class SoftwareTagPk implements Serializable {
#ManyToOne
private Tag tag;
#ManyToOne
private Software software;
...
}
And SoftwareTag class:
#Entity
public class SoftwareTag extends Model {
#EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
#Transient
public Tag getTag() {
return pk.getTag();
}
public void setTag(Tag aTag) {
pk.setTag(aTag);
}
#Transient
public Software getSoftware() {
return pk.getSoftware();
}
public void setSoftware(Software aSoftware) {
pk.setSoftware(aSoftware);
}
}
Also in logs:
Error with association to [class models.Tag] from
[models.SoftwareTagPk.tag]. Is class models.Tag registered?
How to fix it?
To make this code work you have to do:
In your SoftwareTagPk class put only id's of Tag and Software
Move #ManyToOne relations to SoftwareTag class
Add #JoinColumn annotations with attributes updatable and insertable set to false.
Override setters setTag and setSoftware in SoftwareTag class. In these setters you will rewrite id's to composite key.
Main idea of this solution is that SoftwareTag has composite key and #ManyToOne relations and they are mapped to the same collumns.
This is the code:
Tag.java
#Entity
public class Tag extends Model {
#Id
private Integer id;
#OneToMany(mappedBy="tag")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
public static Finder<Integer,Tag> find = new Finder<Integer,Tag>(
Integer.class, Tag.class
);
}
Software.java
#Entity
public class Software extends Model {
#Id
private Integer id;
#OneToMany(mappedBy="software")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
}
SoftwareTag.java
#Entity
public class SoftwareTag extends Model {
SoftwareTag() {
pk = new SoftwareTagPk();
}
#EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
#ManyToOne
#JoinColumn(name = "tag_id", insertable = false, updatable = false)
private Tag tag;
#ManyToOne
#JoinColumn(name = "software_id", insertable = false, updatable = false)
private Software software;
public Tag getTag() {
return tag;
}
public void setTag(Tag aTag) {
tag = aTag;
pk.tag_id = aTag.getId();
}
public Software getSoftware() {
return software;
}
public void setSoftware(Software aSoftware) {
software = aSoftware;
pk.software_id = aSoftware.getId();
}
}
SoftwareTagPk.java
#Embeddable
public class SoftwareTagPk implements Serializable {
public Integer tag_id;
public Integer software_id;
#Override
public int hashCode() {
return tag_id + software_id;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
SoftwareTagPk pk = (SoftwareTagPk)obj;
if(pk == null)
return false;
if (pk.tag_id.equals(tag_id) && pk.software_id.equals(software_id)) {
return true;
}
return false;
}
}