automapping 1:1 mvc unmapped members found - asp.net

I am trying to use automapper to map between my entites db class and my view model. They have the same exact prop names but i get the error thrown saying unmapped members found. From what I understand if you have 1:1 Relationship you do not have to do the manual mapping in the config file. what am I missing here?
product class
public class product
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public int numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public double weight { get; set; }
public int stock { get; set; }
public int stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public int views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public DateTime addedTime { get; set; }
public string updatedBy { get; set; }
public DateTime updatedTime { get; set; }
}
entites class
public partial class newProduct
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public Nullable<int> numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public Nullable<double> weight { get; set; }
public Nullable<int> stock { get; set; }
public Nullable<int> stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public Nullable<int> views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public Nullable<System.DateTime> addedTime { get; set; }
public string updatedBy { get; set; }
public Nullable<System.DateTime> updatedTime { get; set; }
}
Mapping Config
public static void RegisterMaps()
{
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<product, newProduct>();
config.CreateMap<newProduct, product>();
});
}
and the controller
public ActionResult Index()
{
using (StoreEntities db = new StoreEntities())
{
var results = (from p in db.newProducts select p).Where(a => a.active == 1);
var products = AutoMapper.Mapper.Map<product>(results);
return View(products);
}

Related

Cannot deserialize a JSON string using .NET Core

I have recently switched to .NET Core and I am having trouble deserializing the following JSON string into this object. Usually works like a charm using Newtonsoft.
public class smDesktopSearchResultsVM
{
public smDesktopSearchResultsVM()
{
this.indexEventVMs = new List<indexEventVMLite>();
}
public int page { get; set; }
public int totalRecs { get; set; }
public int totalPages { get; set; }
public int? LinkGroupId { get; set; }
public List<indexEventVMLite> indexEventVMs { get; set; }
}
public class indexEventVMLite
{
public indexEventVMLite()
{
this.Event = new EventVMLite();
}
public EventVMLite Event { get; set; }
public int orderCount { get; set; }
public int sortOrder { get; set; }
public string pageImage { get; set; }
public string retinaPageImage { get; set; }
public int linkId { get; set; }
public int linkgroupId { get; set; }
public string pageURL { get; set; }
}
public class EventVMLite
{
public int WebsiteId { get; set; }
public int EventId { get; set; }
public string EventName { get; set; }
public string EventPassword { get; set; }
public DateTime EventDate { get; set; }
public DateTime? EventEndDate { get; set; }
public DateTime? EventExpires { get; set; }
public DateTime? DiscontinuedDate { get; set; }
public DateTime? forceDateDeleted { get; set; }
public bool EventReady { get; set; }
}
Here is the JSON sting:
{
"page": 1,
"totalRecs": 11,
"totalPages": 2,
"indexEventVMs": {
"Event": {
"WebsiteId": 5140,
"EventId": 14614,
"EventName": "Proofpix Elementary School",
"EventPassword": "proofpixelementarydemo",
"EventDate": "2021-08-30T16:00:00",
"EventEndDate": "2021-08-30T20:00:00",
"EventExpires": "2022-09-01T05:00:00",
"DiscontinuedDate": null,
"forceDateDeleted": null,
"EventReady": true
},
"orderCount": 5,
"sortOrder": 1,
"pageImage": "https://s3.us-east-1.wasabisys.com/usstandard.cdn.proofpix.com/websites/5140/PageMedia/266450/Descendants/1939278/680_9099_class-composite-7a.jpg",
"retinaPageImage": null,
"linkId": 354967,
"linkgroupId": 9527,
"pageURL": "https://jackblack.proofpix.com/proofpix-elementary-school/"
},
"LinkGroupId": 9527
}
Here is the error message:
The JSON value could not be converted to System.Collections.Generic.List`1[SortMagic_Desktop.indexEventVMLite]. Path: $.indexEventVMs | LineNumber: 0 | BytePositionInLine: 57.
What is funny is that Visual Studio has no problem parsing the JSON string to JSON when viewing the error data so it must be possible!
The problem can be in the List indexEventVMs a JSON list is [] but in the example it's a object {}.
So according to your JSON the classes would be something like this:
public class Object
{
public long Page { get; set; }
public long TotalRecs { get; set; }
public long TotalPages { get; set; }
public IndexEventVMs IndexEventVMs { get; set; }
public long LinkGroupId { get; set; }
}
public class IndexEventVMs
{
public Event Event { get; set; }
public long OrderCount { get; set; }
public long SortOrder { get; set; }
public Uri PageImage { get; set; }
public object RetinaPageImage { get; set; }
public long LinkId { get; set; }
public long LinkgroupId { get; set; }
public Uri PageUrl { get; set; }
}
public class Event
{
public long WebsiteId { get; set; }
public long EventId { get; set; }
public string EventName { get; set; }
public string EventPassword { get; set; }
public DateTimeOffset EventDate { get; set; }
public DateTimeOffset EventEndDate { get; set; }
public DateTimeOffset EventExpires { get; set; }
public object DiscontinuedDate { get; set; }
public object ForceDateDeleted { get; set; }
public bool EventReady { get; set; }
}
If you need that indexEventVMs receive a list you need to change from the json object {} to an array with object[{}].
You have to replace
public List<indexEventVMLite> indexEventVMs { get; set; }
with this
public indexEventVMLite indexEventVMs { get; set; }
but it is better to try this code
var json = ...your json
var result = JsonConvert.DeserializeObject<smDesktopSearchResultsVM>(json);
var resultSerialized =JsonConvert.SerializeObject(result);
result
{"page":1,"totalRecs":11,"totalPages":2,"indexEventVMs":{"Event":{"WebsiteId":5140,"EventId":14614,"EventName":"Proofpix Elementary School","EventPassword":"proofpixelementarydemo","EventDate":"2021-08-30T16:00:00-02:30","EventEndDate":"2021-08-30T20:00:00-02:30","EventExpires":"2022-09-01T05:00:00-02:30","DiscontinuedDate":null,"forceDateDeleted":null,"EventReady":true},"orderCount":5,"sortOrder":1,"pageImage":"https://s3.us-east-1.wasabisys.com/usstandard.cdn.proofpix.com/websites/5140/PageMedia/266450/Descendant/1939278/680_9099_class-composite-7a.jpg","retinaPageImage":null,"linkId":354967,"linkgroupId":9527,"pageURL":"https://jackblack.proofpix.com/proofpix-elementary-school"},"LinkGroupId":9527}
classes
public partial class smDesktopSearchResultsVM
{
[JsonProperty("page")]
public long Page { get; set; }
[JsonProperty("totalRecs")]
public long TotalRecs { get; set; }
[JsonProperty("totalPages")]
public long TotalPages { get; set; }
[JsonProperty("indexEventVMs")]
public IndexEventVMs IndexEventVMs { get; set; }
[JsonProperty("LinkGroupId")]
public long LinkGroupId { get; set; }
}
public partial class IndexEventVMs
{
[JsonProperty("Event")]
public Event Event { get; set; }
[JsonProperty("orderCount")]
public long OrderCount { get; set; }
[JsonProperty("sortOrder")]
public long SortOrder { get; set; }
[JsonProperty("pageImage")]
public Uri PageImage { get; set; }
[JsonProperty("retinaPageImage")]
public object RetinaPageImage { get; set; }
[JsonProperty("linkId")]
public long LinkId { get; set; }
[JsonProperty("linkgroupId")]
public long LinkgroupId { get; set; }
[JsonProperty("pageURL")]
public Uri PageUrl { get; set; }
}
public partial class Event
{
[JsonProperty("WebsiteId")]
public long WebsiteId { get; set; }
[JsonProperty("EventId")]
public long EventId { get; set; }
[JsonProperty("EventName")]
public string EventName { get; set; }
[JsonProperty("EventPassword")]
public string EventPassword { get; set; }
[JsonProperty("EventDate")]
public DateTimeOffset EventDate { get; set; }
[JsonProperty("EventEndDate")]
public DateTimeOffset EventEndDate { get; set; }
[JsonProperty("EventExpires")]
public DateTimeOffset EventExpires { get; set; }
[JsonProperty("DiscontinuedDate")]
public object DiscontinuedDate { get; set; }
[JsonProperty("forceDateDeleted")]
public object ForceDateDeleted { get; set; }
[JsonProperty("EventReady")]
public bool EventReady { get; set; }
}

How to Create EF one-to-one relationship with Asp.net Identity

Goal: Create a one-to-one relationship between EF Asp.Net.Identity.User and EF UserBusiness
This is my EF Asp.Net.Identity.User:
public class UserEntity:IdentityUser
{
public override string Id { get; set; }
public override string UserName { get; set; }
public override string Email { get; set; }
public override string NormalizedUserName { get; set; }
public override string NormalizedEmail { get; set; }
public string Telephone { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
public DateTime? DateOfBirth { get; set; }
public string NIF { get; set; }
public string Gender { get; set; }
public string Password { get; set; }
public bool IsUserProfileCompleted { get; set; }
**public ICollection<UserBusinessEntity> Business { get; set; }**
public ICollection<PatientEntity> Patients { get; set; }
public DateTime UpdatedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime CreatedOn { get; set; }
My EF UserBusiness:
[Table ("UserBusiness")]
public class UserBusinessEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string BusinessId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public string Fax { get; set; }
public string Owner { get; set; }
public string OwnerPointofContact { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime DeletedOn { get; set; }
public DateTime UpdatedOn { get; set; }
[ForeignKey("Id")]
public string Id { get; set; }
public virtual UserEntity User { get; set; }
}
Repository:
==> RepositoryExtension:
public static IQueryable<UserEntity> BuildUserWithBusiness(this IQueryable<UserEntity> query)
{
return query.Include(u => u.Business);
}
==> Repository
public async Task<UserEntity> GetByIdWithBusinessAsync(string businessId)
{
return await _context.Users
.BuildUserWithBusiness()
.FirstOrDefaultAsync(x => x.Id == businessId);
}
Fluent API:
public class DentalClinicDbContext : IdentityDbContext<UserEntity, UserRoleEntity, string>
{
public DbSet<UserBusinessEntity> UserBusiness { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserEntity>(entity =>
{
entity.ToTable("Users");
});
builder.Entity<UserEntity>(entity =>
{
entity.HasOne(b => b.Business)
.WithOne(u => u.User);
});
I got an error on u.User
Error:
'ICollection' does not contain a definition for 'User' and no accessible extension method 'User' accepting a first argument of type 'Collection could be found (are you missing a using directive or an assembly reference?)
There is a line in your code,
public ICollection<UserBusinessEntity> Business { get; set; }
which should be changed to,
public UserBusinessEntity Business { get; set; }
Also, the model builder should be changed to,
builder.Entity<UserEntity>(entity =>
{
entity.HasOne(b => b.Business)
.WithOne(u => u.User);
.HasForeignKey<BusinessUser>(c => c.Id);
});
Please note that I haven't tried the code real-time.
You should follow this example:
https://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx

Trying to recreate a solution given for a question, need a little assistance

Trying to recreate a solution given for ASP.NET MVC - Taking search criteria as input, and displaying the results, in the same View?, but not sure where to find the querymanager that derloopkat uses in his example.
[HttpPost]
public ActionResult Query(FormQueryModel model)
{
var queryManager = new QueryManager(model);
model.QueryResults = queryManager.GetResults();
return View(model);
}
My ViewModels
public class PartRequestInfoSearch
{
public int? Building { get; set; }
public int? PartType { get; set; }
public int? PartStatus { get; set; }
public Nullable<System.DateTime> tmpStartDate { get; set; }
public Nullable<System.DateTime> tmpEndDate { get; set; }
public int PageSize { get; set; }
public List<RequestedPartInfo> RequestedPartInfos { get; set; }
public PartRequestInfoSearch()
{
this.RequestedPartInfos = new List<RequestedPartInfo>();
}
}
}
public class RequestedPartInfo
{
public int idPartRequest { get; set; }
public string Building { get; set; }
public string RequestNumber { get; set; }
public string PartNumber { get; set; }
public string VendorPartNumber { get; set; }
public string PartDescription { get; set; }
public int StockQTY { get; set; }
public int RequestQTY { get; set; }
public int ShippedQTY { get; set; }
public string PartStatus { get; set; }
}

Cannot save entity one to one EF mvc 5

I am trying to insert a new record into database, no errors, a new record is not created in Applicant and ApplicantNotification table. Not sure what I am doing wrong?
Applicant
[Index]
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Address1 { get; set; }
[Required]
public string Address2 { get; set; }
[Required]
public string Address3 { get; set; }
[Required]
public string Postcode { get; set; }
[Required]
public string CaseReference { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
ApplicantNotification
[Index]
[Key, Column("ApplicantID"), ForeignKey("Applicant")]
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondtNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime ReminderDate { get; set; }
public int ReminderFrequency { get; set; }
[DataType(DataType.Date)]
public DateTime? FirstNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? SecondNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? ThirdNotificationDate { get; set; }
public bool IsArchive { get; set; }
public virtual Applicant Applicant { get; set; }
ViewModel
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
public string ApplicantFirstname { get; set; }
public string ApplicantLastname { get; set; }
public string ApplicantAddress { get; set; }
public string ApplicantAddress1 { get; set; }
public string ApplicantAddress2 { get; set; }
public string ApplicantAddress3 { get; set; }
public string ApplicantPostcode { get; set; }
[Required]
public string ApplicantCaseReference { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ApplicantDateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
/*Notification*/
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime? ReminderDate { get; set; }
Create Method:
// POST: Applicant/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ApplicantNotificationViewModel model)
{
var applicant = new Applicant();
var applicantNotification = new ApplicantNotification();
if (ModelState.IsValid)
{
SetApplicant(model, applicant);
SetApplicantNotification(model, applicantNotification);
using (var context = new WorkSmartContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
db.Applicants.Add(applicant);
context.SaveChanges();
db.ApplicantNotifcations.Add(applicantNotification);
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
return RedirectToAction("Index");
}
}
return View(model);
}
Thanks for the suggestions in the comments.
It appears, if the datetime column is set to allow null, then the datetime either has to be set to null or set to the correct format in order for sql datetime to work. Otherwise it throws the
"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\The statement has been terminated."
https://stackoverflow.com/questions/4608734/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o
I set the dates to null in my Entity objects, and entered a new entry to the database.

Retrieving twitter with json

I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);

Resources