This is my model I want to retrieve all students with each attendances list when class = value and month = November
One approach is to use Include() function of entity framework. In your attendance entity you need connection to the student for example in Attendance.cs:
public int StudentId { get; set; }
And in Student entity you have a collection of attendances:
Student.cs
ICollection<Attendance> Attendances { get; set; }
And in class connection to student:
public int StudentId { get; set; }
public Student Student { get; set; }
Now you have to add sets of these entities to your database context:
ApplicationDbContext.cs
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base("context")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Attendance> Attendances { get; set; }
public DbSet<Class> Classes { get; set; }
}
You can now load your entity with connected entities with:
using (ApplicationDbContext db = new ApplicationDbContext())
{
var result = db.Classes.Where( (clas) => clas.Value == SomeValue)
.Include( (clas) => clas.Student
.Include( (student) => student.Attendances
.Where( (attendance) => attendance.Month == "November") ));
}
Related
I like to create a DB model in ASP.Net Core 3.1. I am using Code First approach with EF Core 3.1.
I like to create a model for this relationship-
So, there is one Employee table and every employee has multiple bosses and each has multiple sub-ordinates. But every boss and every subordinate are employees also. What I have done is something like this-
Employee Model-
public class Employee
{
[HiddenInput(DisplayValue = false), Display(Name = "ID")]
[Key()]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order = 1)]
public Guid? Id { get; set; } = Guid.NewGuid();
[Column("Name"), Required(ErrorMessage = "Term Name should be given"), Display(Name = "Term Name", Prompt = "Please Give Term Name")]
[DataType(DataType.Text)]
public string Name { get; set; }
public ICollection<Boss> Bosses { get; set; }
public ICollection<Subordinate> Subordinates { get; set; }
............
............
}
But I am getting this error during creating the DB model by the command Add-Migration <MigrationName>-
Unable to determine the relationship represented by navigation property 'Employee.Bosses' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Can anyone please help?
direct many-to-many relations are not supported with ef core 3.1.
See this: https://learn.microsoft.com/de-de/ef/core/what-is-new/ef-core-5.0/whatsnew
If you cannot use ef core >= 5, than you have to create a navigation property to the EmployeeBoss entity.
Try this:
public partial class Employee
{
public Employee()
{
EmployeeBossEmployees = new HashSet<EmpoyeeBoss>();
EmployeeBossBosses = new HashSet<EmpoyeeBoss>();
}
[Key]
public int Id { get; set; }
[InverseProperty(nameof(EmpoyeeBoss.Employee))]
public virtual ICollection<EmpoyeeBoss> EmployeeBossEmployees { get; set; }
[InverseProperty(nameof(EmpoyeeBoss.Boss))]
public virtual ICollection<EmpoyeeBoss> EmployeeBossBosses { get; set; }
}
public partial class EmpoyeeBoss
{
[Key]
public int Id { get; set; }
public int BossId { get; set; }
public int EmployeeId { get; set; }
[ForeignKey(nameof(EmployeeId))]
[InverseProperty("EmployeeBossEmployees")]
public virtual Employee Employee { get; set; }
[ForeignKey(nameof(BossId))]
[InverseProperty("EmployeeBossBosses")]
public virtual Employee Boss { get; set; }
}
and include in your dbcontext:
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<EmpoyeeBoss> EmployeeBosses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EmpoyeeBoss>(entity =>
{
entity.HasOne(d => d.Employee)
.WithMany(p => p.EmployeeBossEmployees)
.HasForeignKey(d => d.EmployeeId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.Boss)
.WithMany(p => p.EmployeeBossBosses)
.HasForeignKey(d => d.BossId);
});
I was practicing User.Identity and timestamps functions in ASP.NET MVC 5,
So I created a student class filled some properties, I just wanted to test if it is capturing timestamps and userId, so user id is getting captured and datetime too, problem is whenever I'm editing a record and save it, its created date becomes Null and modified date is updated, please review the code and help.
Thanks in advance.
Below is the Code
{
public class BaseEntity
{
public DateTime? DateCreated { get; set; }
public string UserCreated { get; set; }
public DateTime? DateModified { get; set; }
public string UserModified { get; set; }
}
public class Student : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Subject { get; set; }
public string Class { get; set; }
public Section Section { get; set; }
public byte SectionId { get; set; }
}
then I used Codefirst approach and created an application Database and added this code in Identity Model
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Student> Students { get; set; }
public override int SaveChanges()
{
AddTimestamps();
return base.SaveChanges();
}
//public override async Task<int> SaveChangesAsync()
//{
// AddTimestamps();
// return await base.SaveChangesAsync();
//}
private void AddTimestamps()
{
var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
var currentUsername = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
? HttpContext.Current.User.Identity.Name
: "Anonymous";
foreach (var entity in entities)
{
if (entity.State == EntityState.Added)
{
((BaseEntity)entity.Entity).DateCreated = DateTime.UtcNow;
((BaseEntity)entity.Entity).UserCreated = currentUsername;
}
else
((BaseEntity)entity.Entity).DateModified = DateTime.UtcNow;
((BaseEntity)entity.Entity).UserModified = currentUsername;
}
}
public DbSet<Section> Sections { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
I have created a simple controller with create,edit and dispay actions.
The code you posted doesn't show DateCreated being set to null as far as I can see. I think the issue is when you save an existing record you do not have the DateCreated or UserCreated fields in your view. So when you post the form the MVC model binder doesn't see them and thus sets them to null (I'm assuming your are binding to the Student model in your controller action).
In your edit view add the following hidden fields:
#Html.HiddenFor(model => model.DateCreated)
#Html.HiddenFor(model => model.UserCreated)
Now when you post the form the MVC model binder will bind these values to your model and save them to the database.
My problem is accessing related entities in Web App on 2nd level relation. Didn't find proper answer related to EF7.
Let's take following sample of 3 classes: one-to-many - x - many-to-one.
public class Person {
public int PersonId { get; set; }
public string Name { get; set; }
public virtual ICollection<Buy> Buys { get; set; } = new List<Buy>();
}
public class Buy {
public int BuyId { get; set; }
public int PersonId { get; set; }
public int BookId { get; set; }
public virtual Person Person { get; set; }
public virtual Book Book { get; set; }
}
public class Book {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Buy> Buys { get; set; } = new List<Buy>();
}
With context.
public class MyContext : DbContext {
public DbSet<Person> People { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Buy> Buys { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Person>()
.Collection(c => c.Buys).InverseReference(c => c.Person)
.ForeignKey(c => c.PersonId);
modelBuilder.Entity<Book>()
.Collection(i => i.Buys).InverseReference(i => i.Book)
.ForeignKey(i => i.BookId);
}
Person Controller - Details view.
// _context present in given scope
public IActionResult Details(int? id) {
var person = _context.People
.Include(c => c.Buys)
.Where(c => c.PersonId == id)
.FirstOrDefault();
}
With this configuration I intended to be able to fetch from Person model, not only Buys info, but also related further books. Like following in part of View.
#model <project>.Models.Person
// (...)
#Html.DisplayFor(model => model.PersonId) // ok - person
#Html.DisplayFor(model => model.PersonName) // ok - person
#foreach (var item in Model.Buys) {
#Html.DisplayFor(modeItem => item.BuyId) // ok - buy
#Html.DisplayFor(modelItem => item.Book.Name) // null - book
}
Do I need to code additional references in fluent API or do further includes in entity model to be able to access Item data from Person level?
You should include Book like you did with Buys. I mean:
var person = _context.People
.Include(c => c.Buys.Select(x => x.Book))
.Where(c => c.PersonId == id)
.FirstOrDefault();
But actually if you working with MVC it's better to create ViewModel Class that have all data that you need on particular View rather than have your EF classes on View.
In EF 7 beta7 you can also use the ThenInclude method to include several levels:
var person = _context.People
.Include(c => c.Buys)
.ThenInclude(b=>b.Book)
.FirstOrDefault(c => c.PersonId == id);
This is a follow up to an earlier question.
I want to populate a ViewModel, which has 3 properties, and one list of Occ class (which also has 3 properties.
public class RatesViewModel
{
public string TypeName { get; set; }
public long TypeID { get; set; }
public int TypeCount { get; set; }
public virtual IQueryable<Occ> Occs { get; set; }
}
public class Occ
{
public string occ { get; set; }
public decimal ratetocharge { get; set; }
public int numOfOcc { get; set; }
public virtual RatesViewModel RatesViewModel { get; set; }
}
When I run the following Linq query in LinqPad:
var rooms = tblRoom
.GroupBy(p => p.tblType)
.Select(g => new
{
TypeName = g.Key.type_name,
TypeID = g.Key.type_id,
TypeCount = g.Count(),
Occs = rates.Where(rt => rt.type_id == g.Key.type_id &&
(
(rt.type_id == g.Key.type_id)
))
.GroupBy(rt => rt.occ)
.Select(proj => new
{
occ = proj.Key,
ratetocharge = proj.Sum(s => s.rate),
numOfOcc = proj.Count()
})
});
rooms.Dump();
...as before, it correctly returns the data model I'm looking for:
...and when I click on Occs it drills down into the Occs class:
The complete view in LinqPad is:
My query in Visual Studio is:
var rooms = dbr.Rooms
.GroupBy(p => p.RoomTypes).Select(g => new RatesViewModel
{
TypeName = g.Key.type_name,
TypeID = g.Key.type_id,
TypeCount = g.Count()
,
Occs = db.Rates.Where(rt => rt.type_id == g.Key.type_id &&
(
(rt.type_id == g.Key.type_id)
))
.GroupBy(rt => rt.occ)
.Select(proj => new Occ
{
occ = proj.Key,
ratetocharge = proj.Sum(s => s.rate),
numOfOcc = proj.Count()
})
})
.ToList();
However when running this, I get an error:
The specified LINQ expression contains references to queries that are associated with different contexts.
I think I understand the error - but I'm not sure how to separate the query into 2 separate queries, and then join those query results together again to get my original results set.
My model classes are:
public class Rates
{
public int id { get; set; }
public long type_id { get; set; }
public DateTime ratedate { get; set; }
public decimal rate { get; set; }
public string occ { get; set; }
public List<RoomType> Type { get; set; }
}
public class Rental
{
[Key]
public long rental_id { get; set; }
public long room_id { get; set; }
public DateTime check_in { get; set; }
public DateTime check_out { get; set; }
public virtual Room Room { get; set; }
}
public class Room
{
[Key]
public long room_id { get; set; }
public long type_id { get; set; }
public virtual RoomType RoomTypes { get; set; }
public virtual ICollection<Rental> Rentals { get; set; }
}
public class RoomType
{
[Key]
public long type_id { get; set; }
public string type_name { get; set; }
public IQueryable<Rates> Rates { get; set; }
public virtual ICollection<Room> Room { get; set; }
}
Can anyone help either review my query or models, so it works with one query, or show me how to separate the query into two, and then combine the result sets?
Thank you,
Mark
apitest.Models.RoomContext' does not contain a definition for 'Rates'...
(your comment on hydr's answer)
Well, there you go: not only two different context instances but two different context classes. I suspect your linqpad query was directly against the database connection, which means it used one linq-to-sql DataContext (created on the fly).
You need to use one context class (and one instance of it) in your query. And connect to it in Linqpad to make sure you test the same query provider as Visual Studio.
dbr and db seem to be two different instances of the same context. But in one query you should only use one context. So I would suggest the following:
Occs = dbr.Rates.Where(rt => rt.type_id == g.Key.type_id && ....
If this doesn't help can you quote the lines where you initialize the contexts?
I have two classes. A Company has a County set against it:
public class Company
{
public int Id { get; set; }
public string CompanyName { get; set; }
public Country HomeCountry { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
I am trying to map to an existing database where the Company table contains the foreign key of the Country record. So I presumably need to tell code first the name of the foreign key column.
Below is the complete code example. It's currently failing with different exceptions based on different things that I try. There's seems to be a lack of cohesive documentation on this as yet.
So using Code First Fluent API how do I define the name of the foreign key column?
Test app:
Create database as follows:
CREATE DATABASE CodeFirst;
GO
Use CodeFirst
create table Companies
(
Id int identity(1,1) not null,
HomeCountryId int not null,
Name varchar(20) not null,
constraint PK_Companies primary key clustered (Id)
)
create table Countries
(
Id int identity(1,1) not null
, Code varchar(4) not null
, Name varchar(20) not null
, constraint PK_Countries primary key clustered (Id)
)
alter table Companies
add
constraint FK_Company_HomeCountry foreign key (HomeCountryId)
references Countries (Id) on delete no action
Now run the following C# app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data;
namespace CodeFirstExistingDatabase
{
class Program
{
private const string ConnectionString = #"Server=.\sql2005;Database=CodeFirst;integrated security=SSPI;";
static void Main(string[] args)
{
// Firstly, add a country record, this works fine.
Country country = new Country();
country.Code = "UK";
country.Name = "United Kingdom";
MyContext myContext = new MyContext(ConnectionString);
myContext.Countries.Add(country);
myContext.Entry(country).State = EntityState.Added;
myContext.SaveChanges();
Console.WriteLine("Saved Country");
// Now insert a Company record
Company company = new Company();
company.CompanyName = "AccessUK";
company.HomeCountry = myContext.Countries.First(e => e.Code == "UK");
myContext.Companies.Add(company);
myContext.Entry(company).State = EntityState.Added;
myContext.Entry(country).State = EntityState.Unchanged;
myContext.SaveChanges();
Console.WriteLine("Saved Company"); // If I can get here I'd he happy!
}
}
public class MyContext
: DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Country> Countries { get; set; }
public MyContext(string connectionString)
: base(connectionString)
{
Database.SetInitializer<MyContext>(null);
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CountryConfiguration());
modelBuilder.Configurations.Add(new CompanyConfiguration());
base.OnModelCreating(modelBuilder);
}
}
public class CompanyConfiguration
: EntityTypeConfiguration<Company>
{
public CompanyConfiguration()
: base()
{
HasKey(p => p.Id);
Property(p => p.Id)
.HasColumnName("Id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
Property(p => p.CompanyName)
.HasColumnName("Name")
.IsRequired();
ToTable("Companies");
}
}
public class CountryConfiguration
: EntityTypeConfiguration<Country>
{
/// <summary>
/// Initializes a new instance of the <see cref="CountryConfiguration"/> class.
/// </summary>
public CountryConfiguration()
: base()
{
HasKey(p => p.Id);
Property(p => p.Id)
.HasColumnName("Id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
Property(p => p.Code)
.HasColumnName("Code")
.IsRequired();
Property(p => p.Name)
.HasColumnName("Name")
.IsRequired();
ToTable("Countries");
}
}
public class Company
{
public int Id { get; set; }
public string CompanyName { get; set; }
public Country HomeCountry { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}
The above fails with the following when saving the country:
Invalid column name 'HomeCountry_Id
Any help would be very much appreciated!!
Thanks, Paul.
public CompanyConfiguration()
{
//...
HasRequired(x => x.HomeCountry).WithMany()
.Map(x => x.MapKey("HomeCountryId"));
}
We are moving a Web Forms app to MVC3 using Code First against an existing db without any problems. Here are 2 sample Models and the DbContext I'm using. prDepartments & prCategories map to tables in the db and ApplicationDBContext matches the connection string in Web.config
The DeptID field in prCategory is a Foreign Key to prDepartment - Everything works great
public class prCategory
{
[Key]
public int CatgID { get; set; }
public int DeptID { get; set; }
[Required(ErrorMessage="Category Description Is Required")]
[DisplayName("Desc Name")]
[CssClass("ui-Field-Name")]
public string Description { get; set; }
public string Route { get; set; }
public string OrderBy { get; set; }
public virtual prDepartment Department { get; set; }
public virtual List<prProduct> prProducts { get; set; }
}
public class prDepartment
{
[Key]
public int DeptID { get; set; }
[Required(ErrorMessage = "Department Description Is Required")]
[RequiredMessage("This is the Required Message")]
public string Description { get; set; }
public string Route { get; set; }
public string OrderBy { get; set; }
public virtual List<prCategory> prCategories { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet<prDepartment> prDepartments { get; set; }
public DbSet<prCategory> prCategories { get; set; }
public DbSet<prProduct> prProducts { get; set; }
}