Insert entity and assign foreign key value - c#

PostEntity
[Table("Posts")]
public class PostEntity
{
public PostEntity()
{
ViewsCount = 0;
VotesCount = 0;
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int PostId { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Text { get; set; }
[Required]
public string Permalink { get; set; }
[Required]
public string CreatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public UserEntity CreatedByUser { get; set; }
public List<PostTagEntity> PostTags { get; set; }
public List<PostVoteEntity> PostVotes { get; set; }
public List<PostSpamFlagEntity> PostSpamFlags { get; set; }
public int ViewsCount { get; set; }
public int VotesCount { get; set; }
[Required]
public string PostType { get; set; }
[Required]
public string PostState { get; set; }
public int? CategoryId { get; set; }
[ForeignKey("CategoryId")]
public CategoryEntity Category { get; set; }
public List<ResponseEntity> Responses { get; set; }
}
User entity
public class UserEntity : IdentityUser
{
public async Task<IdentityResult> GenerateUserIdentityAsync(UserManager<UserEntity> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
public String Name { get; set; }
public String Gender { get; set; }
public String ProfilePictureUrl { get; set; }
public String InfoMessage { get; set; }
public String Country { get; set; }
public DateTime BirthDate { get; set; }
public List<PostEntity> Posts { get; set; }
public string LockoutReason { get; set; }
public string LockoutAdditionalComment { get; set; }
}
The problem:
PostEntity post = new PostEntity();
post.CategoryId = request.CategoryId;
post.CreatedAt = DateTime.UtcNow;
post.CreatedByUserId = user.Id; // <-- doesn't work
post.PostType = "B";
post.Title = request.Title;
post.PostState = "N";
post.Permalink = Permalink.Create(request.Title);
post.Text = request.Content;
UpdateBlogpostTags(post, request.Tags);
m_context.Posts.Add(post);
m_context.SaveChanges();
I get:
Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
But if I change:
post.CreatedByUserId = user.Id;
to:
post.CreatedByUser = user;
It inserts successfully.
This also works but feels wrong:
post.CreatedByUser = new UserEntity(){
Id = user.Id
};
What am I missing?

Related

Return Foreign Key Data on Get All Call

I have my unit of measure in the database, when you save a unit, you save the name, id, tenant Id and more to the table, then UnitSize get saved to its own table UnitOfMeasureSize. It shares the UnitOFMeasureId and I need to figure out how to get the the UnitSize back and display it with the UOM name on the interface. I read up on entities and feel like i have it right so I am not sure what I am doing wrong. Any suggestions?
here is my dropdown
namespace Mudman.Data.Entities
{
[Table("UnitOfMeasure")]
public class UnitOfMeasure : IEntityBase, IAuditBase
{
[Key]
[Column("UnitOfMeasureId")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
[Required]
[ForeignKey("TenantId")]
public string TenantId { get; set; }
[JsonIgnore]
public virtual Tenant Tenant { get; set; }
public string Name { get; set; }
public virtual IEnumerable<UnitOfMeasureSize> UnitSize { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
[StringLength(255)]
public string CreateUserId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime UpdateDate { get; set; }
[StringLength(255)]
public string UpdateUserId { get; set; }
}
}
namespace Mudman.Data.Entities
{
[Table("UnitOfMeasureSize")]
public class UnitOfMeasureSize : IEntityBase, IAuditBase
{
[Key]
[Column("UnitOfMeasureSize")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
[Required]
[ForeignKey("TenantId")]
public string TenantId { get; set; }
[JsonIgnore]
public virtual Tenant Tenant { get; set; }
[Required]
[ForeignKey("UnitOfMeasureId")]
public string UnitOfMeasureId { get; set; }
public virtual UnitOfMeasure UnitOfMeasure { get; set; }
[Required]
public int UnitSize { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
[StringLength(255)]
public string CreateUserId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime UpdateDate { get; set; }
[StringLength(255)]
public string UpdateUserId { get; set; }
}
}
public async Task<IEnumerable<UnitOfMeasureViewModel>> GetAllAsync()
{
var result = await _unitOfMeasureRepo.FindByAsync(uom => uom.TenantId == TenantId);
result.OrderBy(r => r.Name);
return _mapper.Map<List<UnitOfMeasure>, List<UnitOfMeasureViewModel>>(result.ToList());
}
Here is how I am trying to grab the Unit Sizes in my AdminStore
public getUnitSizes(unitOfMeasureId: string) {
return this.api.get(`/${unitOfMeasureId}/UnitSize`)
.then(
(data: any) => data,
(error: any) => {throw error;}
);
}
public getUnitSizes = async (unitOfMeasureId: string) => {
const list: any[] = await this.adminAPI.getUnitSizes(unitOfMeasureId);
runInAction(() => {
this.unitSizes = list;
});
}

E.F Core does not return all values When Include another table

public IEnumerable<Parties> GetAll()
{
return database.Parties;
}
Works very well and the output is:
But when I Include another table by foreignkey like this:
public IEnumerable<Parties> GetAll()
{
return database.Parties.Include(i=>i.User);
}
It does not work, it returns first value of the table and nothing else,the output is :
Users.cs :
public partial class Users
{
public Users()
{
Parties = new HashSet<Parties>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string Biography { get; set; }
public string Password { get; set; }
public virtual ICollection<Parties> Parties { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
Parties.cs :
public partial class Parties
{
public Parties()
{
Image = new HashSet<Image>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime PartyDate { get; set; }
public DateTime CreatedDate { get; set; }
public int ParticipantCount { get; set; }
public int MaxParticipant { get; set; }
public string PartySplash { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool EntranceFree { get; set; }
public int? FreeParticipant { get; set; }
public int? FreeParticipantMax { get; set; }
public int UserId { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<Image> Image { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
As you can see on the 2nd picture it interrupts at first row of the table.
I have added this answer based on Vidmantas's comment. ReferenceLoopHandling should be ignored like this in startup.cs:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

Navigation for One to many relationship does no work in c#

I have two entities in my database:Patient and Doctor, which contains one-to-many relationship.Classes are as follows:
public partial class Doctor
{
public Doctor()
{
this.Patients = new HashSet<Patient>();
}
public int DoctorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Country { get; set; }
public System.DateTime Birthday { get; set; }
public byte[] Photo { get; set; }
public string Password { get; set; }
public string PasswordSalt { get; set; }
public int SpecialityID { get; set; }
public virtual Speciality Speciality { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
}
public partial class Patient
{
public int PatientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public string MaritalStatus { get; set; }
public System.DateTime Birthday { get; set; }
public string Phone { get; set; }
public int DoctorID { get; set; }
public System.DateTime EntryDate { get; set; }
public virtual Doctor Doctor { get; set; }
public virtual PatientAddress PatientAddress { get; set; }
}
This is code for adding a patient to a doctor.
public ActionResult AddPatient(PatientViewModel patientVM)
{
using (PeopleCareEntities PeopleEntities=new PeopleCareEntities())
{
PatientAddress patientAddress = Mapper.Map<PatientViewModel, PatientAddress>(patientVM);
Patient patient = Mapper.Map<PatientViewModel, Patient>(patientVM);
int currentDoctor = ((Doctor)Session["Doctor"]).DoctorID;
//problem is here
Doctor doctor=PeopleEntities.Doctors.Single(a=>a.DoctorID==currentDoctor);
var doctorPatients = doctor.Patients.FirstOrDefault(a=>a.Email==patientVM.Email);
if (doctorPatients==null)
{
patient.EntryDate = DateTime.Now;
patient.DoctorID = doctor.DoctorID;
doctor.Patients.Add(patient);
PeopleEntities.SaveChanges();
patientAddress.PatientID = patient.PatientID;
PeopleEntities.PatientAddresses.Add(patientAddress);
PeopleEntities.SaveChanges();
return Json(new { Message = "Patient added successfully !" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { Message="Patient already exist !" }, JsonRequestBehavior.AllowGet);
}
}
}
Adding a patient in database works perfectly,but doctor.Patients has always Count=0. in debug mode.
Thanks in advance.
When loading the doctor entity try this:
Doctor doctor=PeopleEntities.Doctors.Single(a => a.DoctorID == currentDoctor)
.Include(a => a.Patients);

handling circular references when saving(post)

I am stuck with an error i can't figure out. I have a complex model with several circular references. I have tried everything i know to handle them but i am still getting a internal server error (code 500) when i attempt saving.
Below are the models and controllers:
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public Event Event { get; set; }
public RecurrenceType RecurrenceType { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
[StringLength(256)]
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
[Required]
[StringLength(256)]
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public class EventDTO
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public int EventTypeId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int RecurrenceTypeId { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public List<string> UserId { get; set; }
}
public async Task<IHttpActionResult> PostEvent(EventDTO #event)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Event newEvent = new Event();
newEvent.Title = #event.Title;
newEvent.EventTypeId = #event.EventTypeId;
newEvent.CreateDate = #event.CreateDate;
newEvent.UpdateDate = #event.UpdateDate;
newEvent.CreatedBy = #event.CreatedBy;
newEvent.UpdatedBy = #event.CreatedBy;
if (newEvent == null) {
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating Event"));
}
Recurrence recurrence = new Recurrence();
recurrence.StartDate = #event.StartDate;
recurrence.EndDate = #event.EndDate;
recurrence.AllDay = #event.AllDay;
recurrence.StartTime = #event.StartTime;
recurrence.EndTime = #event.EndTime;
recurrence.Venue = #event.Venue;
recurrence.Longitude = #event.Longitude;
recurrence.Latitude = #event.Latitude;
recurrence.RecurrenceTypeId = #event.RecurrenceTypeId;
recurrence.RecurrenceInterval = #event.RecurrenceInterval;
recurrence.ExcludeWeekends = #event.ExcludeWeekends;
recurrence.CreateDate = #event.CreateDate;
recurrence.UpdateDate = #event.UpdateDate;
recurrence.CreatedBy = #event.CreatedBy;
recurrence.UpdatedBy = #event.CreatedBy;
if (recurrence == null)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating recurrence"));
}
var users = db.AspNetUsers.Where(u => #event.UserId.Contains(u.Id));
foreach (var u in users)
recurrence.AspNetUsers.Add(u);
newEvent.Recurrences.Add(recurrence);
db.Events.Add(newEvent);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = #event.Id }, newEvent);
}
When i call the post method i get an internal error code 500 and an error message of "{$id=1, Message=An error has occurred}".

RedisClientManager, An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

I m using RedisClientManager and I m gettin An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll error while trying to set an object
client.Set<ApplicationUser>(user.Id, user);
And User :
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDay { get; set; }
public int BirthPlace { get; set; }
public int TeamId { get; set; }
public int AvatarId { get; set; }
public string Address { get; set; }
public DateTime RegisterationDate { get; set; }
public DateTime CodeSendDate { get; set; }
public string ActivationCode { get; set; }
public string PasswordResetToken { get; set; }
public string FacebookAvatar { get; set; }
public string FacebookId { get; set; }
public bool UseFacebookAvatar { get; set; }
public string IpAddress { get; set; }
public virtual Avatar Avatar { get; set; }
public ApplicationUser()
{
this.Coupons = new HashSet<Coupon>();
}
[JsonIgnore]
public virtual ICollection<Coupon> Coupons { get; set; }
}
The error occure while serialize ApplicationUser, i try to add [JsonIgnore] on ICollection beacuse of nested loop,(Coupon contains user )
I can not find whats the problem ?
I found the solution it works for me.
ApplicationUser object has Coupon and Coupon has ApplicationUser (many to many)
so the serialize going infinite loop.
I add [IgnoreDataMember]
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDay { get; set; }
public int BirthPlace { get; set; }
public int TeamId { get; set; }
public int AvatarId { get; set; }
public string Address { get; set; }
public DateTime RegisterationDate { get; set; }
public DateTime CodeSendDate { get; set; }
public string ActivationCode { get; set; }
public string PasswordResetToken { get; set; }
public string FacebookAvatar { get; set; }
public string FacebookId { get; set; }
public bool UseFacebookAvatar { get; set; }
public string IpAddress { get; set; }
public virtual Avatar Avatar { get; set; }
public ApplicationUser()
{
this.Coupons = new HashSet<Coupon>();
}
[IgnoreDataMember]
public virtual ICollection<Coupon> Coupons { get; set; }
}
Now i can ignore Coupon property so Servis.Stack redisClientManager can seriazlie the object.

Categories

Resources