I'm trying to join three tables in a view model. It works with two tables but crashes when I add a third. Here are the models and the controller. The models section_detail, phone, and department were generated by Entity Framework.
EmployeeViewModel was created by copying properties from the other models. I've abbreviated some of the models shown here with:
public partial class section_detail
{
public int section_detail_id { get; set; }
public Nullable<int> parent_section_det_id { get; set; }
. . .
public string Comments { get; set; }
public string email { get; set; }
public virtual department department { get; set; }
public virtual phone phone { get; set; }
}
public partial class phone
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public phone()
{
this.section_detail = new HashSet<section_detail>();
}
public int phone_id { get; set; }
public string area_code { get; set; }
public string phone_nbr { get; set; }
. . .
public string activity_code { get; set; }
public string function_code { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<section_detail> section_detail { get; set; }
public virtual BudgetUnit BudgetUnit { get; set; }
}
public partial class department
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public department()
{
this.section_detail = new HashSet<section_detail>();
}
public int dept_id { get; set; }
public string description { get; set; }
public string cost_center_code { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<section_detail> section_detail { get; set; }
}
public class EmployeeViewModel
{
public int section_detail_id { get; set; }
public Nullable<int> parent_section_det_id { get; set; }
public Nullable<byte> page_code { get; set; }
public string cost_center_code { get; set; }
public string print_descrip { get; set; }
public Nullable<int> phone_id { get; set; }
public Nullable<int> employee_id { get; set; }
public static explicit operator EmployeeViewModel(List<section_detail> v)
{
throw new NotImplementedException();
}
public string first_name { get; set; }
. . .
public string Comments { get; set; }
public string email { get; set; }
public string description { get; set; }
public string area_code { get; set; }
public string phone_nbr { get; set; }
public string BU { get; set; }
}
Controller:
private vcpds_test1Entities db = new vcpds_test1Entities();
// GET: EmployeeList
public ActionResult Index()
{
List<section_detail> employeeList = db.section_detail.ToList();
List<EmployeeViewModel> employeeVMList = employeeList.Where(emp => emp.page_code == 3)
.Select(emp => new EmployeeViewModel
{
last_name = emp.last_name,
first_name = emp.first_name,
employee_id = emp.employee_id,
phone_nbr = "(" + emp.phone.area_code + ") " + emp.phone.phone_nbr.Substring(0, 3) + "-" + emp.phone.phone_nbr.Substring(3, 4),
BU = emp.phone.BU,
description = emp.department.description,
page_code = emp.page_code
}).OrderBy(emp => emp.last_name).ThenBy(emp => emp.first_name).ToList();
return View(employeeVMList);
}
I get these messages:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
VCPDS2.Models.section_detail.department.get returned null.
If I comment out description = emp.department.description from the controller, then it will return data from the section_detail and phone tables. I've checked the database and the relationships seem ok. I've tried refreshing the models from the database with no change.
It's possible that a emp doesn't have a department so it in itself is null. Description can't be a property of a null. So, what you can simply do is check if it is null first by using null operator:
...
//description = emp.department.description,
description = emp.department?.description ?? "",
...
Basically, if department itself is null, it will stop checking right there, and the ?? shortcut is to use the statement on the right side which is "" if the statement on the left is null.
If you were not expecting an emp not to have a department, you may need to revise your query
Quick edit: You probably need to use an Include in your query so it can bring the department's properties (for description):
List<section_detail> employeeList = db.section_detail
.Include(x => x.department)
.ToList();
Related
I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-
VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)
To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.
Here are the 4 table models :-
public partial class evc_bearer
{
[Key]
[Column(Order = 0]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long evcid { get; set; }
[Key]
[Column(Order = 1]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long bearerid { get; set; }
public int vlan { get; set; }
[Column("ref")]
public string _ref { get; set; }
[Required]
public string port { get; set; }
[Required]
public string endpoint { get; set; }
}
public partial class bearer
{
[Key]
public long id { get; set; }
[Column("ref")]
[Required]
public string _ref { get; set; }
public string name { get; set; }
public long? site { get; set; }
public long? provider { get; set; }
public long? mtu { get; set; }
public float? rental { get; set; }
public int? offsiteprovider { get; set; }
public float? offsiteproviderrental { get; set; }
public bool? aend { get; set; }
public int? equipmentport { get; set; }
public string orderref { get; set; }
public string offsiteref { get; set; }
public string notes { get; set; }
public float? bookingfactor { get; set; }
}
public partial class evc
{
[Key]
public long id { get; set; }
[Required]
public string type { get; set; }
public byte servicetype { get; set; }
public byte cos { get; set; }
public int cir { get; set; }
public int pir { get; set; }
public bool burst { get; set; }
[Column("ref")]
public string _ref { get; set; }
public string orderref { get; set; }
public byte state { get; set; }
public string notes { get; set; }
public float? rental { get; set; }
}
public partial class evc_provider
{
[Key]
public long id { get; set; }
[Required]
public string provider { get; set; }
}
This is the View Model I tried writing :-
public partial class evcBearersVM
{
[Key]
[Column(Order = 0)]
public long evcid { get; set; }
[Key]
[Column(Order = 1)]
public long id { get; set; }
[Column("ref")]
public string b_ref { get; set; }
public string b_name { get; set; }
public string ep_provider { get; set; }
public int eb_vlan { get; set; }
public string eb_port { get; set; }
public string eb_endpoint { get; set; }
}
This is the Linq query I used to populate the View Model :-
IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
join b in csdb.bearers on eb.bearerid equals b.id
join ep in csdb.evc_providers on b.provider equals ep.id
join e in csdb.evcs on eb.evcid equals e.id
where (eb.evcid == evcid && b.id == id)
select new evcBearersVM
{
evcid = eb.evcid,
id = b.id,
b_ref = b._ref,
b_name = b.name,
ep_provider = ep.provider,
eb_vlan = eb.vlan,
eb_port = eb.port,
eb_endpoint = eb._ref
};
So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.
[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
if(b!=null)
{
b.name = model.b_name;
b._ref = model.b_ref;
csdb.SaveChanges();
}
// Update the other entity as well.
return RedirectToAction("Index");
}
I have three simple classes and I am wiring up EF6 to an existing database.
Classes are as follows
namespace Infrastructure.Models
{
[Table("Applications")]
public class Application
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ApplicationID { get; set; }
public DateTime DateTime { get; set; }
public string CompletedZipFileURL { get; set; }
public virtual BusinessInfo BusinessInfo { get; set; }
public Application()
{
this.ApplicationID = Guid.NewGuid();
this.DateTime = DateTime.Now;
this.CompletedZipFileURL = string.Empty;
this.BusinessInfo = new BusinessInfo();
this.BusinessInfo.ApplicationID = this.ApplicationID;
}
}
[Table("BusinessInfo")]
public class BusinessInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }
public Guid ApplicationID { get; set; }
public string BusinessName { get; set; }
public string BusinessType { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string BusinessTelephone { get; set; }
public string FEIN { get; set; }
public string ILSalesTaxNo { get; set; }
public string IncorporateDate { get; set; }
public virtual ApplicantInfo ApplicantInfo {get;set;}
public BusinessInfo()
{
this.BusinessID = Guid.NewGuid();
this.ApplicantInfo = new ApplicantInfo();
this.ApplicantInfo.BusinessID = this.BusinessID;
}
}
public class ApplicantInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ApplicantID { get; set; }
public Guid BusinessID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string HomeAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string EmailAddress { get; set; }
public string PhoneNo { get; set; }
public string Criminal { get; set; }
public ApplicantInfo()
{
this.ApplicantID = Guid.NewGuid();
}
}
}
My Context Class looks like the following:
public class SIDEntities : DbContext
{
public SIDEntities() : base(Settings.GetSetting("ConnectionString"))
{
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<Infrastructure.Models.Application> Application { get; set; }
public virtual DbSet<Infrastructure.Models.BusinessInfo> BusinessInfo { get; set; }
public virtual DbSet<Infrastructure.Models.ApplicantInfo> ApplicantInfo { get; set; }
}
On my existing database, I have the following table names and fields:
Applications (ApplicationID : uniqueidentifier, DateTime : datetime, CompletedZipFileURL : varchar(500))
BusinessInfo (BusinessID : uniqueidentifier, ApplicationID : uniqueidentifier,...)
ApplicationInfo (ApplicantID : uniqueidentifier, BusinessID : uniqueidentifier, ...)
For some reason, as soon as I attempt to do a query against the root Application POCO, I am receiving an error to the effect of "{"Invalid column name 'BusinessInfo_BusinessID'."}".
I have attempted to debug this issue checking out various SO posts but the examples/fixes don't apply to my database first scenario.
The query that is throwing the exception is:
public static Infrastructure.Models.Application Find(Guid id)
{
using (SIDEntities cntx = new SIDEntities())
{
Infrastructure.Models.Application x = new Infrastructure.Models.Application();
//the line below is where the error occurs
x = cntx.Application.Where(m => m.ApplicationID == id).SingleOrDefault();
return x;
}
}
I can see while debugging that the query being generated from LINQ is as follows
SELECT 1 AS [C1],
[Extent1].[ApplicationID] AS [ApplicationID],
[Extent1].[DateTime] AS [DateTime],
[Extent1].[CompletedZipFileURL] AS [CompletedZipFileURL],
[Extent1].[BusinessInfo_BusinessID] AS [BusinessInfo_BusinessID]
FROM [dbo].[Applications] AS [Extent1]
I understand WHY I am getting the error back and that is because there is no "BusinessInfo_BusinessID" column in the Applications table.
I would greatly appreciate any help/pointers that I could get on this one.
Check this out
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }
In your query, change Where and SingleOrDefault to:
x = cntx.Application.SingleOrDefault(m => m.ApplicationID == id);
Hope it helps
I have discovered that because I had a one-to-one relationship (that doesn't technically exist on the SQL server, I had to add a foreign key annotation underneath the [Key] property as noted:
Entity Framework 6: one-to-one relationship with inheritance
and
http://www.entityframeworktutorial.net/entity-relationships.aspx
i have a problem with my join in my asp.net .. i have two database tables.. named APPLICANT and Profile...they have the same fields.. meaning if the Last name in applicant is null the last name is already in profile table. I already connect my program to the applicant table.. but it have so many null fields that have to fetch from the profile data table.... sorry i'm new in asp.net ...
Here's my code in controller:
public View Result Index()
{
var applicants = (from a in db.APPLICANTs
select a).ToList();
return View(applicants);
}
heres my context:
public partial class APPLICANT
{
public int APPLICANT_ID { get; set; }
public Nullable<int> Profile_id { get; set; }
public string APPLICANT_LastName { get; set; }
public string APPLICANT_FirstName { get; set; }
public string APPLICANT_MiddleName { get; set; }
public string APPLICANT_Address { get; set; }
public string APPLICANT_City { get; set; }
public string APPLICANT_ZipCode { get; set; }
public string APPLICANT_Phone { get; set; }
public string APPLICANT_Email { get; set; }
}
public partial class Profile
{
public int PROFILE_ID { get; set; }
public string Applicant_LASTNAME { get; set; }
public string Applicant_FIRSTNAME { get; set; }
public string Applicant_MIDDLENAME { get; set; }
public string Applicant_EMAIL { get; set; }
public string Applicant_PHONE { get; set; }
public string Applicant_ADDRESS { get; set; }
public string Applicant_ZIPCODE { get; set; }
public string Applicant_CITY { get; set; }
}
thanks for those who can help my problem..
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()
}
}
...
}
this is my model
public class Post
{
public long PostID { get; set; }
[Required]
[MaxLength(255)]
public string Title { get; set; }
}
public class Tag
{
public long TagID { get; set; }
[Required]
[Display(Name = "Tag Name")]
[MaxLength(30)]
public string TagName { get; set; }
public bool IsActive { get; set; }
}
public class TagPost
{
public long TagPostID { get; set; }
public long PostID { get; set; }
public long TagID { get; set; }
[ForeignKey("PostID")]
public virtual Post Posts { get; set; }
[ForeignKey("TagID")]
public virtual Tag Tags { get; set; }
}
1) Is this the right many to many configuration in EF 4.1 without mentioning the modelbinder for many to many.
2) if i have completed the many to many configuration using dataannotation why the data is not inserting in tagpost .
public void InsertPostQuestion(Post post,List<string> tags)
{
context.Posts.Add(post);
foreach (string tag in tags)
{
Tag tagr = new Tag();
tagr.TagName = tag;
tagr.IsActive = true;
context.Tags.Add(tagr);
}
context.SaveChanges();
}
3) I do have to define modelbinder to have many to many inserts or delete or update?
modelBuilder.Entity<Post>().
HasMany(c => c.Tags).
WithMany(p => p.Posts).
Map(
m =>
{
m.MapLeftKey("PostID");
m.MapRightKey("TagID");
m.ToTable("TagPost");
});
Change your models to this:
public class Post
{
public long PostID { get; set; }
[Required]
[MaxLength(255)]
public string Title { get; set; }
public bool IsActive { get; set; }
public virtual List<Tag> Tags { get; set; }
}
public class Tag
{
public long TagID { get; set; }
[Required]
[Display(Name = "Tag Name")]
[MaxLength(30)]
public string TagName { get; set; }
public bool IsActive { get; set; }
public virtual List<Post> Posts { get; set; }
}
and then save like so:
public void InsertPostQuestion(Post post,List<string> tags)
{
context.Posts.Add(post);
foreach (string tag in tags)
{
// TODO: If tag has a unique index on TagName, see if it exists first
Tag tagr = new Tag();
tagr.TagName = tag;
tagr.IsActive = true;
context.Tags.Add(tagr);
post.Tags.Add(tagr);
}
context.SaveChanges();
}
EF will create the intermediate table in the db and populate it nicely automatically.