Inheritance mapping asp.net mvc - asp.net-mvc

I have a rather basic problem, but I am searching the best approach for this.
I have two classes:
[Serializable]
public class BudgetEntry
{
public int Id { get; set; }
[StringLength(127)]
public string Name { get; set; }
public int? Category1Id { get; set; }
[Display(Name = "Category 1")]
public Category1Dictionary Category1 { get; set; }
public Category2Dictionary Category2 { get; set; }
public string UserName { get; set; }
public decimal Amount { get; set; }
}
And second one, which derives first one:
public class BudgetEntryViewModel : BudgetEntry
{
public string PeriodName
{
get;
set;
}
}
I have BudgetEntry object, and want to map it as BudgetEntryViewModel.
This is what i tried:
BudgetEntry item = new BudgetEntry() { /*seed data here*/ };
(BudgetEntryViewModel)item;
But this approach causes error:
System.InvalidCastException: 'Unable to cast object of type
'Budget.Models.BudgetEntry' to type
'Budget.Models.BudgetEntryViewModel'.'

Related

Null value assigned when response is written to the Model object

public class BClass
{
public class RClass
{
public string stjCd { get; set; }
public string lgnm { get; set; }
public string stj { get; set; }
public string dty { get; set; }
public List<object> adadr { get; set; }
public string cxdt { get; set; }
public string gstin { get; set; }
public List<string> nba { get; set; }
public string lstupdt { get; set; }
public string rgdt { get; set; }
public string ctb { get; set; }
public Pradr pradr { get; set; }
public string tradeNam { get; set; }
public string sts { get; set; }
public string ctjCd { get; set; }
public string ctj { get; set; }
}
public class AClass
{
public string id { get; set; }
public string consent { get; set; }
public string consent_text { get; set; }
public int env { get; set; }
public string response_code { get; set; }
public string response_msg { get; set; }
public int transaction_status { get; set; }
public string request_timestamp { get; set; }
public string response_timestamp { get; set; }
public RClass result { get; set; }
}
}
//COntroller
BClass.AClass btr = new BClass.AClass();
var lst = JsonConvert.DeserializeObject<BClass.AClass>(strresult);
btr.response_code = lst.response_code;
btr.response_msg = lst.response_msg;
btr.result.lgnm = lst.result.lgnm;
The property btr.result.lgnm = lst.result.lgnm; Gives null value error object reference not set to instance of an object. but the lst variable has a value in the response received.Please provide suggesion
You can solve this by adding one line into your code.
btr.result = new BClass.RClass(); //This one. You need to initialize instance before assigning anything to it.
btr.result.lgnm = lst.result.lgnm;
or else, you can also create default constructor for class A.
public AClass()
{
result = new RClass();
}
I would suggest you to please have a look at below web resources for naming conventions widely used for c# language.
Properties naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members
class naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
Assigning this way does not give null reference exception
RClass rclass=new RClass();
rclass.lgnm=lst.result.lgnm

Flatten Domain Class To ViewModel When Source Is Complex

I am using ValueInjecter to map domain classes to my view models. My domain classes are complex. To borrow an example from this question:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
// VIEW MODEL
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PersonId { get; set; }
public int AddressId { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
I have looked at FlatLoopInjection, but it expects the view model classes to be prefixed with nested domain model type like so:
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
public int AddressId { get; set; }
public string AddressCity { get; set; }
public string AddressState { get; set; }
public string AddressZip { get; set; }
}
The OP in the linked question altered his view models to match the convention expected by FlatLoopInjection. I don't want to do that.
How can I map my domain model to the original unprefixed view model? I suspect that I need to override FlatLoopInjection to remove the prefix, but I am not sure where to do this. I have looked at the source for FlatLoopInjection but I am unsure if I need to alter the Match method or the SetValue method.
you don't need flattening, add the map first:
Mapper.AddMap<Person, PersonViewModel>(src =>
{
var res = new PersonViewModel();
res.InjectFrom(src); // maps properties with same name and type
res.InjectFrom(src.Address);
return res;
});
and after that you can call:
var vm = Mapper.Map<PersonViewModel>(person);

Many to Many relationship code first

Hi I'm trying to create a database in MVC containing a list of Tv shows and Actors associated with them.
Each Tv show can have multiple Actors and an actor can appear on many tv shows. Each actor has a cast name too, for each show they appear in. Here's my models.
public class TvShow
{
public int ShowId { get; set; }
public string Name { get; set; }
public List<Actor> cast { get; set; }
}
public class Actor
{
public int ActorId { get; set; }
public string Name { get; set; }
public List<TvShow> shows { get; set; }
}
public class Cast
{
public int ShowId { get; set; }
public int ActorId { get; set; }
public string CastName { get; set; }
}
public class TvContext : DbContext
{
public DbSet<TvShow> Shows { get; set; }
public DbSet<Actor> Actors { get; set; }
}
I query the database and run the application to create the database for me, but the CastName attribute is not appearing in my linker table. Any help would be greatly appreciated.
How can EF know that you want to use entity Cast as a M:N relation table?
You have to link entity Cast from TvShow and Actor entities when you want to have there an additional property on many to many relationship. So the model can look like this:
public class TvShow
{
public int ShowId { get; set; }
public string Name { get; set; }
public List<Cast> Casts { get; set; }
}
public class Actor
{
public int ActorId { get; set; }
public string Name { get; set; }
public List<Cast> Shows { get; set; }
}
public class Cast
{
public string CastName { get; set; }
public TvShow TwShow { get; set; }
public Actor Actor { get; set; }
}
And you can get list of actors for given TvShow with following query:
twShow.Casts.Select(c => c.Actor);

Getting Error: "A specified Include path is not valid. The EntityType Field' does not declare a navigation property"

Created method:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleField").ToList();
}
With the above method i am trying to fetch all joined(field.fieldid=schedulefield.fieldid) records from both tables. The field table is related with schedulefield table. Sorry if i am not familiar with technical terms.
Field Model:
public partial class Field : DOIEntity
{
public Field()
{
this.FilerResponses = new HashSet<FilerResponse>();
this.ScheduleFields = new HashSet<ScheduleField>();
}
public int FieldId { get; set; }
public string FieldDisplayName { get; set; }
public int FieldTypeId { get; set; }
public string HelpText { get; set; }
public Nullable<bool> OtherTextAllowed { get; set; }
public Nullable<int> ChoiceGroupId { get; set; }
public virtual FieldType FieldType { get; set; }
public virtual ICollection<FilerResponse> FilerResponses { get; set; }
public virtual ICollection<ScheduleField> ScheduleFields { get; set; }
}
ScheduleField Model:
public partial class ScheduleField
{
[Key]
public int ScheduleId { get; set; }
public int FieldId { get; set; }
public byte SortOrder { get; set; }
public Nullable<bool> IsMandatory { get; set; }
public Nullable<int> ParentFieldId { get; set; }
public Nullable<int> ParentChoiceId { get; set; }
public virtual Field Field { get; set; }
public virtual Schedule Schedule { get; set; }
}
When I call the method I am getting this error:
A specified Include path is not valid. The EntityType
'WorldBank.DOI.Data.Field' does not declare a navigation property with
the name 'ScheduleField'.
Why am I getting this error?
You have to use the property name of the Field class in the Include string:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleFields").ToList();
}
This will eager load the ScheduleField objects associated with the Field objects.
Note, you can also eager load many levels. For example, if you want to eager load the schedules of the ScheduleField object as well you would do this:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleFields.Schedule").ToList();
}

PagedList in MVC3 with IQueryable

I can't understand what i'm doing wrong. Every time I'm getting this error:
The entity or complex type 'BusinessLogic.CompanyWithDivisionCount' cannot be constructed in a LINQ to Entities query.
I need to get info from 'Company' table and divisions count of each company from 'Division' table, and then make PagedList. Here is my 'Company' table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using BusinessLogic.Services;
using BusinessLogic.Models.ValidationAttributes;
namespace BusinessLogic.Models
{
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
}
Here is my domain model:
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
public class CompanyWithDivisionCount: Company // I'm using this
{
public int DivisionCount { get; set; }
}
Here is my controller:
public ActionResult CompaniesList(int? page)
{
var pageNumber = page ?? 1;
var companies = companyService.GetCompaniesWithDivisionsCount2();
var model = companies.ToPagedList(pageNumber, PageSize);
return View(model);
}
And here is my service part:
public IQueryable<CompanyWithDivisionCount> GetCompaniesWithDivisionsCount2()
{
return (from c in dataContext.Companies.AsQueryable()
select new CompanyWithDivisionCount
{
Id = c.Id,
Name = c.Name,
Status = c.Status,
EffectiveDate = c.EffectiveDate,
URL = c.URL,
EAP = c.EAP,
EAPCredentials = c.EAPCredentials,
Comments = c.Comments,
DivisionCount = (int)dataContext.Divisions.Where(b => b.CompanyName == c.Name).Count()
});
}
}
Thanks for help!!!
Creator of PagedList here. This has nothing to do with PagedList, but rather is an Entity Framework issue (I'm no expert on Entity Framework, so can't help you there). To confirm that this is true, write a unit test along the following lines:
[Test]
public void ShouldNotThrowAnException()
{
//arrange
var companies = companyService.GetCompaniesWithDivisionsCount2();
//act
var result = companies.ToList();
//assert
//if this line is reached, we win! no exception on call to .ToList()
}
I would consider changing you data model if possible so that instead of relating Companies to Divisions by name strings, instead use a properly maintained foreign key relationship between the two objects (Divisions should contain a CompanyID foreign key). This has a number of benefits (including performance and data integrity) and will almost certainly make your life easier moving forward if you need to make further changes to you app (or if any company ever decides that it may re-brand it's name).
If you create a proper foreign key relationship then your domain model could look like
public class Company
{
...
public virtual ICollection<Division> Divisions{ get; set; }
public int DivisionCount
{
get
{
return this.Divisions.Count()
}
}
...
}

Resources