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
Related
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();
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 am trying to make changes to a database by using Entity Framework (code-first). Everything works fine up until I attempt to save changes, when an error is thrown:
Invalid Column Name BasketID
However, during debugging, looking at the storeDB.BasketItems, the basketitem was actually added.
What am I missing ?
Code:
// Basket is ENTIRELY Empty, add new item and move on.
if (storebasket == null || storebasket.BasketItems.Count == 0)
{
// Add item as is
BasketItem newItem = new BasketItem
{
sellerSKU = basketItem.sellerSKU,
BasketID = basketID,
sellerID = 1,
Quantity = basketItem.Quantity,
Price = basketItem.Price
};
storeDB.BasketItems.Add(newItem);
storeDB.SaveChanges();
}
Database entity:
public class StoreEntities : DbContext
{
public DbSet<Order> Order { get; set; }
public DbSet<OrderItems> OrderItems { get; set; }
public DbSet<Basket> Basket { get; set; }
public DbSet<BasketItem> BasketItems { get; set; }
}
Classes:
public class Basket
{
[Key]
public string BasketID { get; set; }
public virtual IList<BasketItem> BasketItems { get; set; }
public System.DateTime DateCreated { get; set; }
public Guid UserID { get; set; }
}
public class BasketItem
{
[Key]
public int BasketItemID { get; set; }
public virtual string BasketID { get; set; }
[Required]
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
}
OP pasted Edit as Answer:
I have no idea why this fixed the problem, but the program works as expected now
public StoreEntities(): base("storeDBConnectionString")
{
Database.SetInitializer<StoreEntities>(
new DropCreateDatabaseAlways<StoreEntities>());
If you Look at your BasketItem class you set your BasketID as virtual... That causes entity framework not to bind the property to a column. The correct way to do it would be :
public class BasketItem
{
[Key]
public int BasketItemID { get; set; }
public virtual Basket Basket { get; set; }
public string BasketID { get; set; }
[Required]
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
}
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();
}
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()
}
}
...
}