Entity Framework cannot add new data on model - c#

i have a project where i work with a bookshop. And when a user buys a book, i want to add a record in the SoldBooks table with info about the book and the user. But everything is fine with the add except when i want to add the User Id. Visual studio wont allow me to add an int "Cannot Implicitly convert type INT to models.User"
db.SoldBooks.Add(new SoldBook
{
Title = book.Title,
Author = book.Author,
Price = book.Price,
PurchaseDate = DateTime.Now,
CategoryId = catid,
User = 1
});
db.SaveChanges();
But when i check my database the field UserId says its an INT
What should i do to be able to add the User ID to a new record? Thank you
Models/User.cs
class User
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public DateTime LastLogin { get; set; }
public DateTime SessionTimer { get; set; }
public bool IsActive { get; set; }
public bool IsAdmin { get; set; }
}
Models/SoldBook.cs
class SoldBook
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int CategoryId { get; set; }
public int Price { get; set; }
public DateTime PurchaseDate { get; set; }
public User User { get; set; }
}

Make this changes (you have to add info about the ForeignKey so EF can know how both tables are related):
class SoldBook
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int CategoryId { get; set; }
public int Price { get; set; }
public DateTime PurchaseDate { get; set; }
public int IdUser { get; set; }
[ForeignKey("IdUser")]
public User User { get; set; }
}
and then add the record:
db.SoldBooks.Add(new SoldBook
{
Title = book.Title,
Author = book.Author,
Price = book.Price,
PurchaseDate = DateTime.Now,
CategoryId = catid,
IdUser = 1
});
db.SaveChanges();

You should add additional UserId field to your SoldBook object and use it instead of User
public int UserId { get; set; }

Related

Entity Framework Core seed entity problem

I try to add a migration for the below entities and i get the error. I've tried everything to get it to work and i feel like i'm missing something obvious. The code is below
"The seed entity for type 'Bug' cannot be added because no value was provided for the required property 'UserId'"
public class Bug
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BugId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Status Status { get; set; }
public DateTime DateCreated { get; set; }
public User User { get; set; }
}
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
modelBuilder.Entity<Bug>().HasData(
new Bug()
{
BugId = 1,
Title = "TestTitle1",
Description = "Test1Description1",
DateCreated = DateTime.Now,
Status = Status.Closed,
User = new User() { UserId = 1, UserName = "TestUser1" },
}
I have tried the above as well as looking up shadow keys and seperating Bug and User entitities
UPDATE:
Thanks for all your suggestions. I spent a few hours today messing about with it and below is how i managed to get it to work in case anyone else comes across this error.
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UserName { get; set; }
public ICollection<Bug> Bugs{ get; set; }
}
public class Bug
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Status Status { get; set; }
public DateTime DateCreated { get; set; }
public User User { get; set; }
public int UserId { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var user1 = new User()
{
Id = 1,
UserName = "TestUsername1"
};
modelBuilder.Entity<User>().HasData(user1);
modelBuilder.Entity<Bug>().HasData(
new Bug()
{
Id = 1,
Title = "TestTitle1",
Description = "TestDescription1",
DateCreated = DateTime.Now,
Status = Status.Open,
UserId = 1,
});
}

How to fix SqlException: Invalid column name

I'm using EF code first migrations in MVC5 with SQL Server.
I created a post method, I'm posting DTO data from the client and its all fine i believe, but when i try to save the data to the db i get this invalid column name exception on a foreign key property.
This is the first time i actually counter this error. I checked other questions and most answers were related to the [ForeignKey] data annotation but i think i implemented it the right way
This is the Model
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public Category Category { get; set; }
public bool Approved { get; set; }
}
This is the controller ActionResult method
[HttpPost]
public ActionResult AddServiceProvider(ServiceProviderDTO serviceProvider)
{
bool isInDb = _context.ServiceProviders.Any(s => s.Name == serviceProvider.Name) ? true : false;
//var serviceProviderInDb = _context.ServiceProviders.Where(s => s.Name == serviceProvider.Name).FirstOrDefault();
var newServiceProvider = new ServiceProvider();
if (isInDb == false)
{
newServiceProvider = new ServiceProvider
{
Id = Guid.NewGuid(),
Name = serviceProvider.Name,
PhoneNumber = serviceProvider.PhoneNumber,
YearsOfExperiance = serviceProvider.YearsOfExperiance,
Nationality = serviceProvider.Nationality,
CategoryId = serviceProvider.CategoryId,
Active = true,
Approved = serviceProvider.Approved == null ? false : serviceProvider.Approved.Value
};
_context.ServiceProviders.Add(newServiceProvider);
_context.SaveChanges();
}
return RedirectToAction("Index", "Home");
}
The error occurs on _context.SaveChanges();
It states that CategoryId is an invalid column name
This is not the first time that i use code first migrations and i never came across this error before so i really have no idea why this happens!
I would have the model like this.
The ForeignKey attribute belong to the Category property
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
public bool Approved { get; set; }
}
you need delete this property public int CategoryId { get; set; }
your property public Category Category { get; set; } is the ForeignKey and add the DataAnnotations [ForeignKey("CategoryId")]
it would look like this
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public Category Category { get; set; }
public bool Approved { get; set; }
}

How to use identity aspnetusers

I asked a question earlier but I don't think I asked it correctly.
in my asp.net mvc application I am using aspnetusers for my login and registration.
If I have another model for Employees containing their information, How do I connect these two models so when a user logs in, it grabs their information from the employee table to be used. I created the Employees Model with sql server and used ado.net entity data model to use it in visual studio.
Employee Model:
public partial class Employee
{
public int UserID { get; set; }
[Key]
public int EmployeeID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public System.DateTime StartDate { get; set; }
public int RoleID { get; set; }
public int ShiftID { get; set; }
public int AreaID { get; set; }
public int DisciplineID { get; set; }
public int SiteID { get; set; }
public int ALCategory { get; set; }
public int HoursTaken { get; set; }
public Nullable<int> AwardedLeave { get; set; }
public Nullable<int> TotalHoursThisYear { get; set; }
public int HoursCarriedForward { get; set; }
public Nullable<int> EntitlementRemainingThisYear { get; set; }
public string Comments { get; set; }
public int SickLeaveTaken { get; set; }
public Nullable<int> SickLeaveEntitlement { get; set; }
public Nullable<int> SickLeaveEntitlementRemaining { get; set; }
public int StudyLeaveEntitlement { get; set; }
public int StudyLeaveTaken { get; set; }
public Nullable<int> StudyLeaveRemaining { get; set; }
public int ExamLeaveTaken { get; set; }
public int ForceMajeure { get; set; }
public int BereavementLeaveTaken { get; set; }
public int MaternityLeaveTaken { get; set; }
public int ParentalLeaveTaken { get; set; }
public int AdoptionLeaveTaken { get; set; }
public string ManagerEmail { get; set; }
public string AreaManagerEmail { get; set; }
public virtual Area Area { get; set; }
public virtual Discipline Discipline { get; set; }
public virtual Shift Shift { get; set; }
public virtual Site Site { get; set; }
public virtual Employee Employee1 { get; set; }
public virtual Employee Employee2 { get; set; }
}
And the log-in model:
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
So can I connect these two?
Does it matter that I use database first model?
Could I use a Foreign Key to connect by email?
I want to use it for example to filter a table of employees to only show the employees who have the same siteID for the user logged in.
So when a user logs in, I want them to only see employees with the same site as themselves on the employee HTML table.
After successful login, you will get Id of AspNetUser. Take foreign key reference of column Id from AspNetUser table in your Employee table. By doing this, you can achieve expected result. Simply one more thing you need to add in your Employee model as mentioned below:
public virtual ApplicationUser ApplicationUser { get; set; }

Cannot get property of class(ASP.NET MVC)

I have 3 tables
Appointment, Doctors and Appointment_to_Doctor
Here is Appointment class
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Appointment()
{
this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
}
[Key]
public int Id { get; set; }
public string Start_appointment { get; set; }
public string End_appointment { get; set; }
public string Title { get; set; }
public string Type_of_appointment { get; set; }
[ForeignKey("Patient")]
public Nullable<int> Patient_id { get; set; }
public string Kasse { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public virtual Patient Patient { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}
Here is Doctors class
public partial class Doctor
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Doctor()
{
this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
}
[Key]
public int Id { get; set; }
public string Organization { get; set; }
public string Title { get; set; }
public string Sex { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string C_O { get; set; }
public string Street { get; set; }
public string Index { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}
and third class
public partial class Appointments_to_Doctors
{
[Key]
public int Id { get; set; }
public Nullable<int> Doctor_id { get; set; }
public Nullable<int> Appointment_id { get; set; }
[ForeignKey("Appointment_id")]
public virtual Appointment Appointment { get; set; }
[ForeignKey("Doctor_id")]
public virtual Doctor Doctor { get; set; }
}
I need to get id of doctor from select on front , pass it to back end and make select.
So on back-end I have this code.
public JsonResult GetEvents()
{
using (var ctx = new ApplicationDbContext())
{
var eventList = ctx.Appointments.Where(e=> e.Appointments_to_Doctors.).Select(e => new
{
id = e.Id,
title = e.Title,
start = e.Start_appointment.ToString(),
end = e.End_appointment.ToString(),
allDay = false
});
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
}
But here ctx.Appointments.Where(e=> e.Appointments_to_Doctors.) after dot, I cannot write Doctor_id. Why?
I have this
Severity Code Description Project File Line Suppression State
Error CS1061 'ICollection' does not contain a definition for 'Doctor_id' and no extension method 'Doctor_id' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?) RS_Main C:\Users\nemes\Source\Repos\RIS_Project_New\RS_Main\Controllers\CalendarController.cs 105 Active
Thank's for help so much!
But here ctx.Appointments.Where(e=> e.Appointments_to_Doctors.) after dot, I cannot write Doctor_id. Why?
This is because in your Appointments class you have declared the property Appointments_to_Doctors as a collection, which means you will not be able to access individual property members unless if you want to perform some type of method like .Where, or .Any.. etc on those properties.
You need to change that to:
ctx.Appointments_to_Doctors.Where(e=> e.Doctor_Id.Value == yourValue).Select(e => new
{
id = /* your value */,
title = /* your value */,
start = /* your value */,
end = /* your value */,
allDay = false
});
See, this line performs the .Where method on the Doctor_Id.Value.
Let me know if this helps!
I have similar code that works for me in the application that I am working on, try to add this public int Doctor_id in the appointments for doctors table, same for appointments in the same table.
Basically, I believe that you need to store the Id for appointments and doctors

Save complexa data using entity framework

Hi every one I want to save complex data using Entity Framework and C#. I have 2 classes Product and Order defined as follows
Product Class
public class Product
{
[Key]
public int Id { get; set; }
public string SKU_Code { get; set; }
public string Product_Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Image { get; set; }
public DateTime Created_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
Order Class
public class Order
{
[Key]
public long ID { get; set; }
public string Order_Id { get; set; }
public string Payment_Type { get; set; }
public string Customer_Name { get; set; }
public string Shipping_Address { get; set; }
public DateTime Order_Date { get; set; }
public DateTime Modified_Date { get; set; }
public bool Flag { get; set; }
public List<Product> ProductDetails { get; set; }
}
And I want to save data Order details and my piece of code is as follows.
public Order Add(Order odrerDetails)
{
using (var context = new EcommerceDBContext())
{
var MyOrder_Id = Helper.Random(7); //Generate random orderID from my class
foreach (var detail in odrerDetails.ProductDetails)
{
odrerDetails.Order_Id = MyOrder_Id;
odrerDetails.Quantity = Convert.ToInt32(detail.Quantity);
odrerDetails.Amount = Convert.ToDouble(detail.Price);
//Other Details
context.objOrderListing.Add(odrerDetails);
}
context.SaveChanges();
return odrerDetails;
}
}
This gives me perfect data but when it comes to context.SaveChanges(); it return's me error.
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
To me you domain model seems all wrong. The order should just be used for grouping, its a typical e-commerce scenario.
When you get a receipt of your purchases, you get one receipt with every Item and price listed next to it. Its considered as one order of multiple things, not multiple orders of multiple things.
Reading your last comment, you cant have multiple orders with the same order id. Try to understand the domain first before trying to solve it with code. Also,you have no notion of a Customer with an Order.
public class Product
{
[Key]
public int Id { get; set; }
public string SKU_Code { get; set; }
public string Product_Name { get; set; }
public string Price { get; set; }
public string Image { get; set; }
public DateTime Created_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
public class Order
{
[Key]
public long ID { get; set; }
public string Order_Id { get; set; }
public string Payment_Type { get; set; }
public string Customer_Name { get; set; }
public string Shipping_Address { get; set; }
public DateTime Order_Date { get; set; }
public DateTime Modified_Date { get; set; }
public bool Flag { get; set; }
public List<OrderLineItem> Items { get; set; }
}
public class OrderLineItem
{
[Key]
public long ID { get; set; }
public long Order_Id { get; set; }
public long Product_Id {get; set;}
public int Quantity {get; set;}
}

Categories

Resources