EmployeeDataContext class not pulling data from Database - sql-server

below is my code
I am trying to pull data from database using entityframework.
EmployeeDataContext class -
namespace _09032020_1.Models
{
public class EmployeeDataContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Employee model -
namespace _09032020_1.Models
{
[Table("TbleEmployee")]
public class Employee
{
public int employeeId { get; set; }
public string employeeName { get; set; }
public string employeeCity { get; set; }
public string employeeGender { get; set; }
public int departmentId { get; set; }
}
}
below are the table columns.
here is the controller code
namespace _09032020_1.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Index()
{
EmployeeDataContext employeeDataContext = new EmployeeDataContext();
Employee employee = new Employee();
List<Employee> employees1 = new List<Employee>();
employees1 = employeeDataContext.Employees.ToList();
return View(employees1);
}
}
}
I am not getting data inside employeeDataContext
Please let me know if more info regarding config file requires.

Create the table w data. The first column is primary key and identity.
In an MVC project (you can use another type, also I am showing database first, and you can use another type, right click on the Models folder and add ADO.NET Entity Data Model named EmployeeDataContext. Choose EF Designer from database. New connection, and choose your db. Save connection as EmployeeDataContext and choose your table.
Put this in your code:
using (EmployeeDataContext context = new EmployeeDataContext())
{
var emps = context.Employees.ToList();
}

I got my answer,
I have written wrong table name as model attribute [Table("TbleEmployee")]
My table name is TblEmplyee. So it should be [Table("TblEmployee")]
As I changed this I abled to proceed forward.

Related

Entity Framework Core one to many related data navigation property is always empty

I feel like I'm missing something obvious here; I'm using .Net 5 with Entity Framework Core. The problem is that the foreign key is correct, but the associated navigation property is always empty and has no data. Do I have to do something with the fluent framework, or do something special with my includes?
I have 3 simplified entities and a database context method in this example, the project is much too large to include entirely. In the method, CalendarEvents is a DbSet:
public class CalendarEvent: IJsonSerializable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/// <summary>
/// Gets the personnel associated with this event
/// </summary>
public virtual List<SchedulePerson> SchedulePeople { get; set; } = new List<SchedulePerson>();
}
public class SchedulePerson : IJsonSerializable, ICloneable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
public virtual CalendarEvent AssociatedCalendarEvent { get; set; }
}
public class Employee : IJsonSerializable
{
[Key]
public int Id { get; set; }
public virtual List<SchedulePerson> AssociatedSchedulePeople { get; set; } = new List<SchedulePerson>();
}
public class DbContext : DbContext
{
public DbSet<CalendarEvent> CalendarEvents { get; set; }
public DbSet<SchedulePerson> SchedulePeople { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbContext(DbContextOptions<VibrationContext> options): base(options)
{
}
public CalendarEvent GetEvent(int calendarEventId)
{
var currentCalEvent = this.CalendarEvents.Where(x => x.Id == calendarEventId);
var dummy1 = currentCalEvent.FirstOrDefault();
var dummy2 = currentCalEvent.Include(calEvent => calEvent.SchedulePeople).ToList();
var dummy3 = currentCalEvent.Include(calEvent => calEvent.SchedulePeople).ThenInclude(people => people.Employee).ToList();
return currentCalEvent.FirstOrDefault();
}
}
In this case Employee is the associated navigation property, and the associated key EmployeeId, is correct. For the moment I've added extra logic that will populate each employee per schedule person separately, manually based on the foreign key EmployeeId, when I get the event, but I'd rather not have to add logic like that each time. If that's something unavoidable then that's fine, but I'd like to do things properly and let Entity Framework Core handle as much as possible.
For additional context:
SchedulePerson -> CalendarEvent is a many-to-one relationship
Employee -> SchedulePerson is a many-to-one relationship
In other words a calendar event can contain many schedule persons, but a schedule person can only be associated with one calendar event.
Employee can be associated with many schedule persons, but each schedule person is only associated with one employee.
There should only be one employee for each real person, but there can be multiple SchedulePersons for each real person.
Thank you for your help and let me know if there is any more information I can provide.
Also if anything else looks bad or wrong in these code snippets please let me know.
Edit, this is what I have to do if I want to get the employees in my request:
private void UpdateEmployeeContents(CalendarEvent calendarEvent)
{
foreach (SchedulePerson person in calendarEvent.SchedulePeople)
{
person.Employee = this.Employees.Where(x => x.Id == person.EmployeeId).FirstOrDefault();
}
}

Is there a way to take First() from a hierarchy table in Entity Framework Core?

Is there any way to access a table that is a hierarchy?
Entity Framework Core returns null from the First() method, the table is NOT empty. I use SQL Server to store the table.
public class TestProjectEFDbContext : DbContext
{
private const string connectionString = #"data source=DESKTOP-I2JBLKP; Initial Catalog=TestProjectEF; Trusted_Connection=True; ";
public TestProjectEFDbContext() { }
public TestProjectEFDbContext(DbContextOptions options) : base(options) { }
public DbSet<University> Universities { get; set; }
public DbSet<MedicineUniversity> MedicineUniversities { get; set; }
public DbSet<ArtUniversity> ArtUniversities { get; set; }
public DbSet<TechUniveristy> TechUniveristies { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString);
}
}
var FirstUniversity = testProjectEFDbContext.Universities.First(); // throws an error
The InvalidOperationException: Sequence contains no elements When appeared that you have not any records in the mapped table.
And it is disappeared when you use FirstOrDefault() extension method.
So, double-check the database and table that you are using in the connection string and you have checked that have records.
Also, beware of Table Attribute: [Table(string name, Properties:[Schema = string])

Is it possible to have another object type as a property of SQL Server entity without using relation

I have smaller separate models I don't want to map to SQL Server database table. Is it possible to use them as properties of an object that's mapped to SQL Server table?
I know SQL Server is relational, but of a case where I don't to map these separate models to database table? I have done it several times with non relational databases like MongoDb.
Here is and example what I want to achieve
The DbContext class:
public class ApplicationDbContext: DbContext
{
....
public DbSet<User> Users {get; set;}
}
User class:
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public LoginProfile LoginProfile { get; set; }
}
LoginProfile class:
public class LoginProfile
{
public string Username { get; set; }
public string Password { get; set; }
}
In the above example User model class is the only one I want to have as table in my database. Is it possible to do that, and do things like
var password = user.LoginProfile.Password;
user.LoginProfile.username = "username";

Entity Framework auto assign FK to reference Entity during insertion?

Could you please explain for me Why and How EF auto assign FK to reference entity when i insert entities into Database? I got these simple Entities like this:
First one is Catalogue
public class Catalogue
{
public int CatalogueId { get; set; }
public string Name { get; set; }
public ICollection<Page> Pages { get; set; }
}
Second one is Page which reference to Catalogue.
public class Page
{
public int PageId { get; set; }
public string Name { get; set; }
public int CatalogueId { get; set; }
public Catalogue Catalogue { get; set; }
}
The relationship in this case is one to many. So in the code i am using this:
using (var context = new MyDbContext())
{
var catalogue = new Catalogue
{
Name = "catalogue 1"
};
var page = new Page
{
Name = "page 1",
CatalogueId = 0
};
context.Catalogues.Add(catalogue);
context.Pages.Add(page);
context.SaveChanges();
}
The MyDbContext is simple nothing special.
When i run this code i am expecting it will generate an error because CatalogueId = 0 is not valid, but it working fine,.
It is interesting me and hopefully someone can clarify that :).
Thanks in advance
This is how EF work under the hood. The context will go and execute the INSERT and generate the update for the FK value in the table. Later, will populate the tracked entity with the real key value.
You can experiment with unattached entities and will notice that no FK value is updated.

Cannot save multiple files to database with Foreign Key

In my MVC application I have two tables called Ticket and Attachment and I want to save attachments for per ticket. The problem is that: I need to save multiple attachments with the TicketID when creating a new ticket. So, I think I should create a new ticket in the Ticket table and then get its ID and save all the attachments with this TicketID to the Attachment table in a loop. I have look at many web sites and stackoverflow, but there is not such a kind of problem or solution on that pages. Any idea?
Note: I use Entity Framework Code First, but I can also use Stored Procedure or SQL command for this operation.
Here are these two models:
public class Ticket
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
//... removed for clarifty
}
public class Attachment
{
[Key]
public int ID { get; set; }
//Foreign key for Ticket
public int TicketID { get; set; }
public byte[] FileData { get; set; }
public string FileMimeType { get; set; }
}
And the controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] TicketViewModel viewModel
/* contains both model: Ticket and Attachment */, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//??? First I need to save Ticket
repository.SaveTicket(viewModel.Ticket);
foreach(var f in files)
{
viewModel.Attachment.FileMimeType = f.ContentType;
viewModel.Attachment.FileData = new byte[f.ContentLength];
f.InputStream.Read(viewModel.Attachment.FileData , 0, f.ContentLength);
//??? Then save all attachment. But no idea how to get TicketID
repository.SaveAttachment(viewModel.Attachment);
}
}
return View();
}
The ID property will be automatically filled by EF after a SaveChanges. Your code can then use it. I assume that the viewModel.Ticket object is the actual object saved to the database. If not, please also post the SaveTicket method.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] TicketViewModel viewModel
/* contains both model: Ticket and Attachment */, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
// assumes viewModel.Ticket is the actual entity saved, and SaveChanges is called.
repository.SaveTicket(viewModel.Ticket);
foreach(var f in files)
{
viewModel.Attachment.FileMimeType = f.ContentType;
viewModel.Attachment.FileData = new byte[f.ContentLength];
f.InputStream.Read(viewModel.Attachment.FileData , 0, f.ContentLength);
// fill ticket id
viewModel.Attachment.TicketID = viewModel.Ticket.ID;
repository.SaveAttachment(viewModel.Attachment);
}
}
return View();
}
If you want to do everything in one transaction, you can add the childs immediatly, and SaveChanges will save all objects:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] TicketViewModel viewModel
/* contains both model: Ticket and Attachment */, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
var ticket = viewModel.Ticket;
foreach(var f in files)
{
var attachment = new Attachment();
attachment.FileMimeType = f.ContentType;
attachment.FileData = new byte[f.ContentLength];
f.InputStream.Read(attachment.FileData , 0, f.ContentLength);
ticket.Attachments.Add(attachment);
}
// this will save the ticket and attachments
repository.SaveTicket(ticket);
}
return View();
}
Your Ticket class will have to look like this:
public class Ticket
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
// EF will now to use the foreign key to the attachment table
public virtual ICollection<Attachment> Attachments { get; set; }
}

Resources