Get next pPrimary key id with lambda expression - entity-framework

I'm using Entity Framework 5 and I need to get next id in table like
1
2
3
4
I want to get next id, when my id is 1 want to get next id 2
public class Level
{
[Key]
public int LevelID { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
public int Statue { get; set; }
public int CourseID { get; set; }
public int? SessionCount { get; set; }
public int? SessionAttend { get; set; }
public DateTime? DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
}
Thanks for your help.

public int getNextId(int id)
{
var nextEntities = repository.Query<Levels>().OrderBy(d=>d.LevelId)
.Where(l=>l.LevelId>id)
.Take(1).SingleOrDefault();
return nextEntities != null ? nextEntities.LevelId : ++id; //or return 0 on your choice
}

To get the next LevelId that would be assigned for a new row you could probably use this:
var nextId = db.Levels.OrderBy(x => x.LevelId).Last().LevelId + 1;
I probably wouldn't recommend this though. The whole idea wreaks of bad code smell to me.

Related

Accessing a count of a child's child properties

I have a three classes District, PostalCode and Premise. District contains a virtual list of postalcodes and the postal code class contains a virtual list of premises, from within the district controller is there any was of calculating the number of premises which are in the district, classes as follows:
public class District
{
[Key]
public int DistrictID { get; set; }
public string Name { get; set; }
public int Households { get; set; }
public int Population { get; set; }
public virtual List<PostalCode> PostalCodes { get; set; }
}
public class PostalCode
{
[Key]
public int PostalCodeID { get; set; }
public string FullPostcode { get; set; }
public bool InUse { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public int Easting { get; set; }
public int Northing { get; set; }
public string GridReference { get; set; }
public string Ward { get; set; }
public string Parish { get; set; }
[Display(Name = "Introduced")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Introduced { get; set; }
[Display(Name = "Terminated")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Terminated { get; set; }
public int Altitude { get; set; }
public string Country { get; set; }
[Display(Name = "Last Updated")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? LastUpdated { get; set; }
public string Quality { get; set; }
public string LSOACode { get; set; }
public bool Processed { get; set; }
[Display(Name = "Last Visited")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? LastVisited { get; set; }
public string SalesRep { get; set; }
public virtual List<Premise> Premises { get; set; }
public int? DistrictID { get; set; }
public virtual District District { get; set; }
}
public class Premise
{
[Key]
public int PremiseID { get; set; }
public string MPRN { get; set; }
public string MeterPointAddress { get; set; }
public string DUoSGroup { get; set; }
public string MeterConfigurationCode { get; set; }
public string MeterPointStatus { get; set; }
public int PostalCodeID { get; set; }
public virtual PostalCode PostalCode { get; set; }
public bool Live { get; set; }
public bool Pending { get; set; }
}
I am able to access the list of postal codes within the view of the district controller by using the following code:
#item.PostalCodes.Count()
I thought that I may have been able to use #item.PostalCodes.All().Premises.Count() or some variation of that but this is not being allowed by the compiler, is there any way that this can be accessing the third level premises class from within the district controller?
You can use Include and 2 foreach loops for this. Take a look at this article
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public virtual List<Invoice> Invoices { get; set; }
}
public class Invoice
{
public int InvoiceID { get; set; }
public DateTime Date { get; set; }
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
public class Item
{
public int ItemID { get; set; }
public string Name { get; set; }
public int InvoiceID { get; set; }
public virtual Invoice Invoice { get; set; }
}
And get data:
using (var context = new MyContext())
{
var list = context.Customers.ToList();
foreach (var customer in list)
{
Console.WriteLine("Customer Name: {0}", customer.Name);
foreach (var customerInvoice in customer.Invoices)
{
var items=customerInvoice.Items.Tolist();
}
}
}
Create a partial class District and add a couple field to this partial class:
public partial class District
{
[NotMapped]
public int PostaCodeCount
[NotMapped]
public int PremissesCount
}
Try this query inside of your controller:
var rowDistricts=db.Districts
.Include(pc=>pc.PostalCodes)
.ThenInclude(pr => pr.Premisses)
.ToList();
var districts= new List<District>();
foreach (var item in rowDistricts)
{
item.PostalCodeCount=item.PostalCodes.Count();
item.PremissesCount=item.Premisses.Count();
item.Premisses=null;
item.PostalCodes=null;
districts.Add(item);
}
return View(districts);

EF-Core query but value missing, even it show in database

here is the simple query code...
var order = await _context.ProductOrders
.FirstOrDefaultAsync(x => x.Id == orderId.ToInt());
This is the entity of ProdictOrders
public class ProductOrder
{
public int Id { get; set; }
public int MovieTicketEnrollmentId { get; set; }
public string ProductOrderStatusCode { get; set; }
public int? InvoiceId { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime? UpdateDate { get; set; }
public string UpdateBy { get; set; }
/**
* Navigation Property
*/
public MovieTicketEnrollment MovieTicketEnrollment { get; set; }
public ProductOrderStatus ProductOrderStatus { get; set; }
public ICollection<ProductOrderItem> ProductOrderItems { get; set; }
public Invoice Invoice { get; set; }
}
This data in the database
And what I got after executing query command above... what's just happening here?
MovieTicketEnrollmentId should equal to 1

How do I get a response based on two different IDs in my API?

public class Report
{
[Key]
public int ReportId { get; set; }
[ForeignKey("Subjects")]
public int SubjectId { get; set; }
public Subjects Subjects { get; set; }
[ForeignKey("Teacher")]
public int TeacherId { get; set; }
public Teacher Teacher { get; set; }
[ForeignKey("MarkType")]
public int MarkTypeId { get; set; }
public MarkType MarkType { get; set; }
}
public class Teacher
{
[Key]
public int TeacherId { get; set; }
[MaxLength(50)]
[Required]
public string FName { get; set; }
[MaxLength(50)]
[Required]
public string LName { get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
[MaxLength(50)]
[Required]
public string FName { get; set; }
[MaxLength(50)]
[Required]
public string LName { get; set; }
[ForeignKey("Grade")]
public int GradeId { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
[Key]
public int GradeId { get; set; }
public int StudentGrade { get; set; }
}
public class Subjects
{
[Key]
public int SubjectId { get; set; }
[MaxLength(50)]
[Required]
public string SubjectName { get; set; }
}
public class Terms
{
[Key]
public int TermId { get; set; }
public int Term { get; set; }
}
public class MarkType
{
[Key]
public int MarkTypeId { get; set; }
[MaxLength(20)]
[Required]
public string TypeName { get; set; }
}
public class StudentMark
{
[Key]
public int StudentMarkId { get; set; }
[ForeignKey("Report")]
public int ReportId { get; set; }
public Report Report { get; set; }
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
public int Mark { get; set; }
[ForeignKey("Terms")]
public int TermId { get; set; }
public Terms Terms { get; set; }
}
In the API I am making I want to have the ability to use two different IDs to get a more specific response.
var report = ReportDBContext.StudentMark
.Include(p => p.Student.Grade).Include(p => p.Report)
.Include(p => p.Terms).Include(a => a.Report.Subjects).Include(a => a.Terms)
.Include(a => a.Report.MarkType).Include(a => a.Report.Teacher).ToList();
This allowed me to get StudentMark as well as it's related entities but I want to have the ability to use The student's Id and the Term's Id to get a student's marks for that term and all the subjects related to the student. I am a beginner to Web API so please let me know if I need to add more context.
If you want to query by either StudentId or TermId, I suggest that you provide two different endpoints for these two different queries. Use LINQ Where to check your conditions.
public StudentMark[] GetMarksByStudentId(int studentId) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.StudentId == studentId)
.ToArray();
}
public StudentMark[] GetMarksByTermId(int termId) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.TermId == termId)
.ToArray();
}
If you want to query by StudentId and TermId simultaneously, introduce a query object to encapsulate your parameters. You can test for multiple conditions in the Where clause with AND &&.
public StudentMark[] FindMarks(StudentMarkQuery query) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.StudentId == query.StudentId
&& mark.TermId == query.TermId)
.ToArray();
}
The StudentMarkQuery class is introduced so you can add additional parameters without changing the overall signature of the endpoint:
public class StudentMarkQuery {
public int StudentId { get; set; }
public int TermId { get; set; }
}

EF code first model not in sync with database

My EF Code First model for some reason is not in sync with the db. I'm getting this error:
{"Invalid column name 'Type_Id1'."}
The field is actually called 'Type_Id' so I'm not sure from where that 1 comes up. I have the table column called as Type_Id and also I've added a Type_Id in my type entity model.
Why might I be getting that error message, plus why I'm getting 1 at the end of the name?
Update
My Task class:
public class Task
{
public Task()
{
Language = 1;
Grades = new HashSet<Grade>();
Categories = new HashSet<Category>();
Subjects = new HashSet<Subject>();
Rooms = new Collection<Room>();
Tools = new Collection<Tool>();
}
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual TaskType Type { get; set; }
public string Rules { get; set; }
[Required]
[StringLength(200), MinLength(1)]
public string Name { get; set; }
public int PreperationTime { get; set; }
public int InstructionTime { get; set; }
public int TaskTime { get; set; }
public int Type_Id { get; set; }
public string VideoLink { get; set; }
[Required]
public int Language { get; set; }
public int? MinimumParticipants { get; set; }
public int? MaximumParticipants { get; set; }
public int? Rating { get; set; }
[Required]
public string CreatedBy { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<Tool> Tools { get; set; }
}
DBContext class:
public ApplicationDbContext() : base("DefaultConnection", false)
{
}
public DbSet<Task> Tasks { get; set; }
public DbSet<TaskType> TaskTypes { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
You need to add the FK attribute on your navigation property. EF is creating Type_Id1 because Type_Id already exists (although it can't tell by convention it is the FK).
[ForeignKey("Type_Id")]
public virtual TaskType Type { get; set; }
https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships

Entity Framework 4.3 CF many - to - many relationship saving object?

When creating many to many relationship using EF 4.3 code first approach, I cannot save data to connecting table, also cannot any examples on how to fill this table using saving object to Icollection... Here is my example:
MODELS
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
}
public class Project: DbContext
{
public DbSet<Hospital> Hospitals { get; set; }
public DbSet<Operator> Operators { get; set; }
}
CONTROLLER
public void AddOperater()
{
Hospital h = new Hospital();
h = db.Hospitals.Single(a=>a.Id ==1);
var o = new Operator();
o.FirstName = "John";
o.LastName = "Doe";
o.Dob = new DateTime(1988,2,12);
o.Email = "johndoe#gmail.com";
o.Hospitals.Add(h);
db.SaveChanges();
}
With this approach I keep getting error here: o.Hospitals.Add(h); even when my Hospital instance is filled with data. How exactly to save data to both tables, the dbo.Operators and dbo.OperatorHospital which is relationship table?
o.Hospitals.Add(h) will fail because the list is a null list. You cannot call Add() on a null list. Typically most people get around this by instantiating the list in the constructor of the entity... like so... the current line is blowing up due to a CSharp issue.
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
public Hospital()
{
Operators = new List<Operator>();
}
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
public Operator()
{
Hospitals = new List<Hospital>();
}
}