I have a code first model with 2 table :
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public virtual ICollection<User> User { get; set; }
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual int CompanyId { get; set; }
public Company Company { get; set; }
}
I want select Company with User Object with Stored Procedure
SELECT a.*,u.* FROM [dbo].[Companies] as a
INNER JOIN dbo.Users u on u.CompanyId=a.CompanyId
CompanyDB c = new CompanyDB();
var cc = c.Database.SqlQuery<Company>("dbo.Company_Select")
My problem : cc.User is Null ???
First, you have virtual in the wrong place for User:
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
Second, why the stored procedure? When properly configured you can do:
var companiesWithUsers = db.Companys.Include(c => c.User).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
Please look at my sample code below:
public class LoginModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class RegisterModel
{
[Key]
public int RegisterId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
}
There are many records in the cart table added by many users.
But i want to show the own record of a user from the cart table if he is logged in..how can I do this??
You have to insert a foreign-key property to your Cart class:
public class UserModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
public virtual UserModel User { get; set; } // <-- added
}
Then you can use LINQ to query the Cart-items for a specific user:
var cartItems = dbContext.Cart.Where(a => a.User == loggedInUser);
var query = from a in db.Pages
where a.title.Contains(myTitle)
select a;
var item=query.FirstOrDefault();
if(item!=null)
return View(item);
else
return View("NotFound");
I'm learning ASP.NET MVC 4 with Entity Framework (Database First) and ran into a problem that I'm not able to solve.
I have following tables:
Student: To store students information
Course: To store courses running in an institute
StudentCourse: To store which student selected what course
Fees: To store submitted fees by a student corresponding to StudentCourse
Now, I wan't to show course name, course fees, total fees submitted & the pending fees of students
I'm using Entity Framework in the project and trying to execute a query like this:
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.id)
.Select(m => new { StudentCourseId = m.Key, SumOfFees = m.Sum(v => v.fees) });
I want to get Course object instead of StudentCourseId so that i can display the course, its course fees and total fees submitted by student.
In case, I'm listing all of the four class contents:
Student
public partial class Student
{
public Student()
{
this.Leaves = new HashSet<Leave>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string first_name { get; set; }
public string middle_name { get; set; }
public string last_name { get; set; }
public string password { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string facebook { get; set; }
public string contact_number { get; set; }
public string address { get; set; }
public string admin { get; set; }
public string college { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string descripton { get; set; }
public virtual ICollection<Leave> Leaves { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
Course
public partial class Course
{
public Course()
{
this.CourseContents = new HashSet<CourseContent>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string course_name { get; set; }
public int course_fees { get; set; }
public int duration { get; set; }
public string admin { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual ICollection<CourseContent> CourseContents { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
StudentCourse
public partial class StudentCourse
{
public StudentCourse()
{
this.Fees1 = new HashSet<Fee>();
this.Issues = new HashSet<Issue>();
}
public int id { get; set; }
public int student_id { get; set; }
public int course_id { get; set; }
public int fees { get; set; }
public System.DateTime join_date { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string status { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Fee> Fees1 { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual Student Student { get; set; }
}
Fee
public partial class Fee
{
public int id { get; set; }
public int student_course_id { get; set; }
public int fees { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual StudentCourse StudentCourse { get; set; }
}
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.Course)
.Select(m => new { Course = m.Key, SumOfFees = m.Sum(v => v.fees) });
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..