Previous question link
Consider to my previous question (I put a link to it) I need to get some different information.
Here is a DB structure I only added navigation property
public virtual ICollection<Accident> Accidents { get; set; }
to Transport class
public class Person
{
[Key]
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Transport
{
[Key]
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public virtual ICollection<Accident> Accidents { get; set; }
}
public class Accident
{
[Key]
public int AccsidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
[ForeignKey("TransportID")]
public virtual Transport Transport { get; set; }
public int PersonID { get; set; }
[ForeignKey("PersonID")]
public virtual Person Person { get; set; }
}
public class AccsidentObject
{
[Key]
public int AccidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
If I want to get all accidents I use
var accidents = DBContext.Accidents.Select( a => new AccidentObject
{
AccidentID = a.AccidentId,
AccidentDate
TransportID
Model
Brand = a.Transport.Brand,
PersonID = a.Person.PersonID,
FirstName
LastName
});
What would be a code if I would like to select TransportObject with added specific Accident data
public class TransportObject
{
[Key]
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public int AccidentID { get; set; }
public DateTime AccidentDate { get; set; }
}
Use this code
var transports = DBContext.Transports
.SelectMany(
x => x.Accidents,
(t, a) => new TransportObject
{
TransportID = t.TransportID,
Model = t.Model,
Brand = t.Brand,
AccidentID = a.AccidentId,
AccidentDate = a.AccidentDate
}
);
More about select many in MSDN.
Related
I have a parent object(brand) with list of 5 child object(campaign):
Brand response = await _brandRepository.GetAsync(request.Id);
//other properties mapped fine, but Campaing is null..
var result = _mapper.Map<BrandDto>(response);
return result;
I have these definations for mapping:
CreateMap<Domain.Entity.Campaign, CampaignDto>();
CreateMap<Domain.Entity.Brand, BrandDto>();
objects:
public class BrandDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<CampaignDto> Campaing { get; set; }
}
public class CampaignDto
{
public int Id { get; set; }
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public CampaignDto ParentCampaign { get; set; }
public BrandDto Brand { get; set; }
}
entities:
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
public class Campaign : SqlEntityBase
{
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public Guid ImpressionId { get; set; }
public string Name { get; set; }
public EntryStatus Status { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public Brand Brand { get; set; }
public Campaign ParentCampaign { get; set; }
}
If I map child object manually it works fine, but its not cool
how can I make this proper way?
I am trying to map a model to a view, but I receive the error above when I am trying to display all my elements, since Automapper doesn't recognize the IEnumerable I think. I receive the error when I am trying to map FixedAssets to FixedAssetsView and FixedAssetsView to FixedAssets.
Here are the objects I am trying to map:
FixedAssets
public class FixedAssets : IEntityBase
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<Category> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set;
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
public FixedAssets()
{
this.category = new HashSet<Category>();
}
}
FixedAssetsView
public class FixedAssetsView
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<CategoryView> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set; }
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
}
Category
public class Category : IEntityBase
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssets> fixedasset { get; set; }
public Category()
{
this.fixedasset = new HashSet<FixedAssets>();
}
}
CategoryView
public class CategoryView
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssetsView> fixedasset { get; set; }
}
Automapper configuration
Mapper.Initialize(x =>
{
x.CreateMap<FixedAssets, FixedAssetsView>();
x.CreateMap<FixedAssetsView, FixedAssets>();
x.CreateMap<Category, CategoryView>();
x.CreateMap<CategoryView, Category>();
});
I believe you need a .ForMember in your Mapper initialization.
eg:
Mapper.CreateMap<IEnumerable<Source>, IEnumerable<Target>>()
.ForMember(f => f, mp => mp.MapFrom(
mfrom => mfrom.Select(s => AutoMapper.Mapper.Map(s, new Target())
)
);
My question is about how can i select some one-two column from those tables are included and at the end when i am selecting as list it is returning list of parent object but child are contain those column i mention to select?
var testq = _db.Homes
.Include(x => x.Indexs.Cities.Proviences.Regions)
.Include(x => x.Images)
.Select(x => new Homes {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
At the end I need to have list of home model (List) and just images and Address and region name have value and important just those are selected from database not all infromation in the tables. I am trying to make a query with better performance
Edit Add Models
public partial class dbContext : DbContext
{
public virtual DbSet<City> Cities { get; set; }
public virtual DbSet<Province> Provinces { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Index> Indexs { get; set; }
public virtual DbSet<Home> Homes { get; set; }
public virtual DbSet<Images> Imageses { get; set; }
}
public partial class Home
{
public Home()
{
Imageses = new HashSet<Images>();
}
[Key]
public int IDHome { get; set; }
[Required]
[StringLength(5)]
public string Cap { get; set; }
[Required]
[StringLength(10)]
public string Number { get; set; }
[Required]
[StringLength(50)]
public string Address { get; set; }
....
public virtual Index Indexs { get; set; }
public virtual ICollection<Images> Imageses { get; set; }
}
public class Index
{
public int ID { get; set; }
public int IDHome { get; set; }
....
public virtual City Cities { get; set; }
}
public partial class City
{
[Key]
public int ID { get; set; }
public int IDProvincia { get; set; }
public decimal Latitudine { get; set; }
public decimal Longitudine { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
....
public virtual Province Provinces { get; set; }
}
public partial class Province
{
[Key]
public int ID { get; set; }
public int IDRegione { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(3)]
public string Init { get; set; }
...
public virtual Region Regions { get; set; }
}
public partial class Region
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public DateTime DataInsert { get; set; }
...
}
public class Images
{
public int ID { get; set; }
public string Path { get; set; }
...
}
absolutely tables have more column just add here as example
you have to define a new type with the fields you need, or use an anonymous type.
.Select(x => new {
Images = x.Images,
Address = x.Address,
Indexs.Cities.Proviences.Regions =
x.Indexs.Cities.Proviences.Regions.Name });
Hi guys I am spinning wheels on this one. I am using EF6 and ASP.Net 4.6. I have a given table which has student information and parent information. A student can have many parents and a parent can have many students. Call this table 'Contact'. I am to create a table called 'Request' which will hold information for a parent submitting a request for his student. I will create a lookup table with two columns, one for student id and one for parent id called 'StudentParents'. I want to be able to have the parent log in, select his student from a drop down of all of his students and submit the request. The many to many relationship is throwing me off as far as my include statements. How can I get EF to set up this structure so that when I GetRequest(id) I can get the Student info and the Parent info to be included? Here is my code that wont Include anything other than the request.
public class Contact
{
[Key]
public int id { get; set; }
public string student_id { get; set; }//This is the Student ID
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public string grade { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_first_name { get; set; }
[Display(Name = "Parent Middle Name")]
public string contact_middle_name { get; set; }
[Display(Name = "Parent Last Name")]
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
[Display(Name = "Parent Email")]
public string contact_email { get; set; }
[Display(Name = "Parent Address")]
public string login { get; set; }//This is the Parent ID
public string Classif_description { get; set; }
}
public class Request
{
[Key]
public int id { get; set; }
public Student student_id { get; set; }
public Contact login { get; set; }
[Display(Name = "First School Choice")]
public string firstSchool { get; set; }
[Display(Name = "Second School Choice")]
public string secSchool { get; set; }
[Display(Name = "Rising Grade")]
public string rising_grade { get; set; }
public DateTime ReqSubmitted { get; set; }
public string ReqStatus { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public string ModifBy { get; set; }
}
public class Parent
{
public int id { get; set; }
public string contact_first_name { get; set; }
public string contact_middle_name { get; set; }
public string contact_last_name { get; set; }
public string contact_relationship { get; set; }
public string contact_email { get; set; }
public string contact_address { get; set; }
public string contact_city { get; set; }
public string contact_zip { get; set; }
[Key]
public string login { get; set; }
public string contact_pw { get; set; }
public string phone { get; set; }
public string phone_type { get; set; }
public Parent() { }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public int id { get; set; }
public int student_id { get; set; }
public string last_name { get; set; }
public string first_name { get; set; }
public string middle_initial { get; set; }
public DateTime birthdate { get; set; }
public string gender { get; set; }
public string grade { get; set; }
public string Fed_race_description { get; set; }
public string Classif_description { get; set; }
public int current_school_id { get; set; }
public string current_school_name { get; set; }
public int home_school_id { get; set; }
public string home_school_name { get; set; }
public Student()
{
this.Parents = new HashSet<Parent>();
}
public virtual ICollection<Parent> Parents { get; set; }
}
public class OEContext : DbContext
{
public OEContext() : base("name=OEContext")
{
}
public DbSet<Request> Requests { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.HasMany(s => s.Students)
.WithMany()
.Map(x =>
{
x.MapLeftKey("login");
x.MapRightKey("student_id");
x.ToTable("StudentParents");
}
);
base.OnModelCreating(modelBuilder);
}
}
Changed the strategy. Made Request have many Contacts. So I added a constructor to the request:
public Request()
{
Contacts = new List<Contact>();
}
public virtual ICollection<Contact> Contacts { get; set; }
Next I changed the contact class:
public int ContactId { get; set; }
public Contact() { }
public virtual Request Request { get; set; }
With this relationship I can pull both Parents and a student from the Contacts associated with the Request.
Most tutorials don't really cover this at all. They just say link your entity to a controller and you're done.
In my business model I have Customers and I have Customer Contacts 1 Customer to >1 Customer Contacts. How do I create a view model for these that will allow them to be edited/created/whatever from the same view?
public class Customer
{
public Customer()
{
this.CustomerContacts = new List<CustomerContact>();
this.Systems = new List<System>();
this.CreatedByCustomerTickets = new List<Ticket>();
this.CustomerTickets = new List<Ticket>();
}
public long CustomerID { get; set; }
public Nullable<bool> BusinessCustomer { get; set; }
public string CustomerName { get; set; }
public string CustomerNotes { get; set; }
public virtual ICollection<CustomerContact> CustomerContacts { get; set; }
public virtual ICollection<System> Systems { get; set; }
public virtual ICollection<Ticket> CreatedByCustomerTickets { get; set; }
public virtual ICollection<Ticket> CustomerTickets { get; set; }
}
public class CustomerContact
{
public long CustomerContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Phone { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public Nullable<int> Zip { get; set; }
public Nullable<long> CustomerID { get; set; }
public string Email { get; set; }
public bool PromotionalEmails { get; set; }
public virtual Customer Customer { get; set; }
}
Well I'd start with this
public class CustomerViewModel
{
public Customer Customer {get; set;}
public CustomerContact CustomerContact {get; set;}
}
and work from there.
If you don't need all the properties from the domain objects, you may consider something more like:
public class CustomerViewModel
{
public long CustomerID { get; set; }
public ICollection<CustomerContact> CustomerContacts { get; set; }
}
It's really up to you to construct your view models in a way that will meet the needs of your specific project.