.NET 5.0 - EF - DbSet is empty after upgrade from 3.1 - entity-framework

One of my DbSet returns an empty list, while data is there in db, and it used to work before upgrading to .NET 5.0
var list = await context.TeamMembers.ToListAsync(); >> returns empty list
var list = await context.TeamMembers.Include(t=>t.User).ToListAsync(); >> returns empty list
while others are working correctly returning a populated list
var list2 = await context.Users.ToListAsync(); >> works fine
my dbsets are define like this
public DbSet<User> Users { get; set; }
public DbSet<TeamMember> TeamMembers { get; set; }
here is my table structure
CREATE TABLE [dbo].[teamMembers] (
[Id] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[UserId] INT NOT NULL,
[PartnerId] INT NOT NULL,
[Type] INT NOT NULL,
[CreationDate] DATETIME DEFAULT (getdate()) NOT NULL,
[ModificationUserId] INT NOT NULL,
[ModificationDate] DATETIME DEFAULT (getdate()) NOT NULL,
CONSTRAINT [FK_teamMembers_Members] FOREIGN KEY ([UserId]) REFERENCES [users]([Id]),
CONSTRAINT [FK_teamMembers_Partners] FOREIGN KEY ([PartnerId]) REFERENCES [partners]([Id]),
CONSTRAINT [FK_teamMembers_ModificationUser] FOREIGN KEY ([ModificationUserId]) REFERENCES [users]([Id]),
);
and here is my object
[Table("teamMembers")]
public class TeamMember
{
[Required]
public int? Id { get; set; }
[Required]
public User User { get; set; }
[Required]
public int? PartnerId { get; set; }
[Required]
public int Type { get; set; } // 0 agency 1 Salesman
[Required]
public DateTime CreationDate { get; set; }
[Required]
public DateTime ModificationDate { get; set; }
[Required]
public int ModificationUserId { get; set; }
}
[edit]
here is the query generated by EF, if I run it manualy it returns data
(there is a joint in this one as I used .Include(...) )
SELECT [t].[Id], [t].[CreationDate], [t].[ModificationDate], [t].[ModificationUserId], [t].[PartnerId], [t].[Type], [t].[UserId], [u].[Id], [u].[Civility], [u].[CreationDate], [u].[CreationUserId], [u].[Email], [u].[FirstName], [u].[Identifier], [u].[Language], [u].[LastName], [u].[Login], [u].[LoginEnabled], [u].[Mobile], [u].[ModificationDate], [u].[ModificationUserId], [u].[MustResetPassword], [u].[Password], [u].[Phone], [u].[Position], [u].[ResetPasswordDate], [u].[ResetPasswordToken], [u].[RoleId], [u].[Type]
FROM [teamMembers] AS [t]
LEFT JOIN [users] AS [u] ON [t].[UserId] = [u].[Id]
here is the User class
public class User
{
[Required]
public int? Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Email { get; set; }
public string Login { get; set; }
[Required]
public DateTime CreationDate { get; set; }
[Required]
public DateTime ModificationDate { get; set; }
[Required]
public int CreationUserId { get; set; }
[Required]
public int ModificationUserId { get; set; }
[Required]
public short RoleId { get; set; }
[Required]
public short Civility { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
[Required]
public string Position { get; set; }
[Required]
public short Language { get; set; }
[Required]
public bool MustResetPassword { get; set; }
[Required]
public short Type { get; set; } // professional/private
public string Identifier { get; set; }
[JsonIgnore]
public string Password { get; set; }
[Column(TypeName = "BIT")]
public bool LoginEnabled { get; set; }
public string ResetPasswordToken { get; set; }
public DateTime? ResetPasswordDate { get; set; }
}
here is the partner class
public class Partner
{
[Required]
public int? Id { get; set; }
public Company Company { get; set; }
[Required]
public User Manager { get; set; }
public List<Invoice> Invoices { get; set; }
[NotMapped]
public double InvoicesAmount { get; set; }
[Required]
public List<ProductRetribution> ProductsRetributions { get; set; }
[Required]
public double Won { get; set; }
[Required]
public double Pending { get; set; }
[Required]
public double Offset { get; set; }
// following fields are created by the system, inputs from client are discarded, no validation , but needed for mvc
[Required]
public DateTime CreationDate { get; set; }
[Required]
public DateTime ModificationDate { get; set; }
[Required]
public int ModificationUserId { get; set; }
}
is there anything I am missing ?
thanks for your help

as it turns out, I was checking the wrong db
the actual db has it's table completely empty
moral of the story : don't mix 3 versions of your database on the dev server
thanks for everyone helping me out, I'll surely fix all my nullables in my tables

Related

Adding an entity in EF Core

I am using EF Core db first approach, .NET6. I have the following classes:
public class Doctor
{
[Key]
public int DoctorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Specialization { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Designation { get; set; }
public bool IsDeleted { get; set; }
}
and
public class Patient
{
[Key]
public int PatientId { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string NIC { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
public DateTime DOB { get; set; }
public string Gender { get; set; }
public string Reference { get; set; }
public short SerialNumberYear { get; set; }
public int SerialNumber { get; set; }
[Required]
public int DoctorId { get; set; } //need to assign Primary doc. Is this correct?
public Doctor Doctor { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public string CreatedBy { get; set; }
public List<Doctor> SecondaryDoctors { get; set; }//need to assign a list of secondary docs. is this correct?
public bool SMS_Allowed { get; set; }
public bool Email_Allowed { get; set; }
public string SpecialConcern1 { get; set; }
public string SpecialConcern2 { get; set; }
public string SpecialConcern3 { get; set; }
public string SpecialConcern4 { get; set; }
}
The Patient class needs to have a Primary doctor assigned and a list of Secondary doctors assigned. What entries should I make in the Patient class to accomodate this requirement? I tried the entries shown above with comments. Is that correct? When I add a patient with this code, I get the following error when creating a new patient record:
Duplicate entry '1' for key 'doctors.PRIMARY'
So when creating a patient, why is efcore trying to create a doctor record?

Error in creating a controller file

I am using Entity Framework. I have tried everything, searching and adding keys but Ienter image description here cannot understand what the problem is and how to resolve it.
public class Reservation
{
[Key]
public int BookingID { get; set; }
public int CustomerID { get; set; }
public int RoomID { get; set; }
public string BookingDate { get; set; }
public int Check_In { get; set; }
public int Check_Out { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public int NoOfNights { get; set; }
[ForeignKey("RoomID")]
public virtual Room Rooms { get; set; }
[ForeignKey("CustomerID")]
public virtual CustomerDetails CustomerDetail { get; set; }
public virtual ICollection<Payment> Payment { get; set; }
}
public class CustomerDetails
{
[Key]
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int PostCode { get; set; }
public string State { get; set; }
public int PhoneNumber { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
enter image description here
All tables need a primary key or you can't use Entity Framework.

EntityFramework One-To-Many fK?

BasketItem duplicateBasketItem = (from ph in storeDB.BasketItems
where ph.sellerSKU == newItem.sellerSKU
select ph).SingleOrDefault();
{"Invalid column name 'BasketID'."}
My Classes:
public class Basket
{
[Key]
public string BasketID { get; set; }
public virtual IList<BasketItem> BasketItems { get; set; }
public int? Count { get; set; }
public System.DateTime DateCreated { get; set; }
public Guid UserID { get; set; }
}
public class BasketItem
{
[Key]
public int BasketItemID { get; set; }
public virtual string BasketID { get; set; }
[Required]
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
}
From the research i have done so far, the error is being cause due to relationships not being mapped properly. How would I map the relationship using modelbuilder
Each basket can(optional) contain many basketitems
Each BasketItem has a BaskedID(FK) to map back to the individual Basket.

Table with INSERT statement conflict in totally different table

I am getting the following error.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.NotificationObject_dbo.Comment_CommentReplyID". The conflict occurred in database "DB_f0f7b19b55c44199988352815f71b25c", table "dbo.Comment", column 'CommentID'.
I'm confused, because the NotificationObject table can have a wide variety of optional foreign keys, including a key to a comment, or a reply to a comment. When I try to add a row with a CommentReplyID, it gives the error above... about the comment table??? The key should point to the CommentReply table, so I'm pretty confused.
See the related models below.
public class NotificationObject
{
public int ID { get; set; }
public int NotificationTypeID { get; set; }
public int? CommentID { get; set; }
public int? CommentVoteID { get; set; }
public int? CommentReplyID { get; set; }
public int? CommentReplyVoteID { get; set; }
public int? UserID { get; set; }
public int? ActivityCommentID { get; set; }
public DateTime DateCreated { get; set; }
public virtual NotificationType NotificationType { get; set; }
public virtual Comment Comment { get; set; }
public virtual Comment CommentVote { get; set; }
public virtual Comment CommentReply { get; set; }
public virtual Comment CommentReplyVote { get; set; }
public virtual ActivityComment ActivityComment { get; set; }
public virtual ICollection<NotificationActor> NotificationActor { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public int ProjectDocID { get; set; }
public int UserID { get; set; }
public string text { get; set; }
public string quote { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<CommentVote> CommentVote { get; set; }
public virtual ICollection<CommentReply> CommentReply { get; set; }
public virtual ICollection<CommentReport> CommentReport { get; set; }
public virtual ProjectDoc ProjectDoc { get; set; }
public virtual User User { get; set; }
public virtual ICollection<ranges> ranges { get; set; }
}
Why wont it let me add a value to the CommentReplyID field in the NotificationObject table?
Your CommentReply navigation property in NotificationObject targets Comment type, not CommentReply type.

One to One with attributes EF codefirst

I am trying to link two models with One to One relationship
the classes are following:
public class Customer : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[ForeignKey("Account")]
public int AccountId { get; set; }
public virtual Account Account { get; set; }
[Required(AllowEmptyStrings = false)]
public string Address { get; set; }
[Required(AllowEmptyStrings = false)]
public string PublicName { get; set; }
[Required]
public int UserId { get; set; }
[ForeignKey("Id")]
[InverseProperty("Customer")]
public virtual User User { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
public class User : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(32)]
[RegularExpression(#"^[\w]+(\.?[\w\d_]+)?$")]
public string Login { get; set; }
[Required]
[MinLength(6)]
[DataType(DataType.Password)]
[RegularExpression(#"^[\w]+(\.?[\w\d_]+)?$")]
public string Password { get; set; }
[Required]
[StringLength(32)]
[DataType(DataType.EmailAddress)]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
public string Email { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[MaxLength(256)]
public string ProfilePhoto { get; set; }
[Required]
[ForeignKey("Account")]
public int AccountId { get; set; }
[Required]
public virtual Account Account { get; set; }
[InverseProperty("User")]
public virtual ICollection<Rate> Rates { get; set; }
public int CustomerId { get; set; }
[ForeignKey("Id")]
[InverseProperty("User")]
public virtual Customer Customer { get; set; }
}
i searched did not but found solution for doing than ONLY with attributes. can anybody help me with that?
Thanks in advance!
The mistake that you're making is that you have both tables pointing to each other as having a foreign key relationship with the other. You have to pick one table as the base table and the other as being the one that has the FK in it. If you want the User table to be the base then you would do the following:
On the User class: Remove the [ForeignKey] and [InverseProperty] attributes from Customer.
On the Customer class:
[Key, ForeignKey("User")]
public int Id { get; set; }
//Other fields
public virtual User User { get; set; }