AspNetUsers as foreign key in another table - entity-framework

Now I am building a mini blog. when user create a post I want to insert user id from AspNetUsers in post table as a foreign key
here the post model, so can anyone tell me the steps to make it.
public class Post
{
[Required]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public string Path { get; set; }
[Required]
public DateTime PostDate { get; set; }
public ApplicationUser User { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}

You have to use the below code to use AspNetUsersId as a foreign key. You can use [Required] if you don't want to make AspNetUsersId as nullable.
public AspNetUsers User { get; set; }
[ForeignKey("AspNetUsersId")]
[Required]
public int AspNetUsersId { get; set; }
Yes, you have to manually set the AspNetUsersId when you are inserting the record in Post table.
Lets say you have object of class Post as obj. So you have to write the below code in your method, if AspNetUsers table PK is Id.
obj.AspNetUsersId = AspNetUsers.Id;

Related

Entity Frameworks Creates Auto Column

I am having a problem in Entity Framework. Entity Framework is generating auto column in sql-server and I am not geting how to make insert operation in that particuler column.
For Example in Teacher class,
public class Teacher
{
[Key]
public String Email { set; get; }
public String Name { set; get; }
public List<TeacherBasicInformation> Teacher_Basic_Information { set; get; } = new List<TeacherBasicInformation>();
public String Password { set; get; }
public List<Course> course { set; get; } = new List<Course>();
[JsonIgnore]
public String JWT_Token { set; get; }
[NotMapped]
[Compare("Password")]
public String ConfrimPassword { set; get; }
}
And in TeacherBasicInformation class ,
public class TeacherBasicInformation
{
[Key]
public int ID { set; get; }
[Required]
[MaxLength(20)]
public String Phone { set; get; }
[Required]
[MaxLength(100)]
public String Address { set; get; }
}
After the migration in the sql server, in TeacherBasicInformation table a auto column is created named 'TeacherEmail'. How Can I insert data into this column using form in asp.net core.
In order to prevent auto-generated columns for FK, use [ForeignKey("YourForeignKey")] on the related table in the entity class:
public int TeacherId { get; set; }
[ForeignKey("TeacherId")]
public virtual Teacher Teacher { get; set; }
It looks like you have the email column set up as the primary key column in your Teacher class, and the related database column. If that's the case, you're going to have trouble with it as it will need to be unique to that record, and primary keys aren't designed to be changed. It can be done in certain scenarios but isn't a best practice.
Perhaps a better approach is to have the [Key] attribute on a property of public int Id { get; set; } so they primary key is now a discrete number instead of an email address. Then you can access, set, and update the email address on each record, without interfering with the key at all.

EF 6 cycles or multiple cascade paths

I'm trying to create my database from my models, but I keep getting the error Introducing FOREIGN KEY constraint 'FK_dbo.Reports_dbo.UserProfiles_UserId' on table 'Reports' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
anyone knows what might be wrong with my models/setup?
These are all used Models
public class Report {
[Key]
public int Id { get; set; }
[Required]
public string Number { get; set; }
public bool Synced { get; set; }
public DateTime CreationDate { get; set; }
public int NewCommentId { get; set; }
public virtual Comment NewComment { get; set; }
public int UserId { get; set; }
public virtual UserProfile User { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Photo> PhotosBefore { get; set; }
public virtual ICollection<Photo> PhotosAfter { get; set; }
}
public class Photo {
[Key]
public int Id { get; set; }
public string Image { get; set; }
public bool Synced { get; set; }
public DateTime CreationDate { get; set; }
public int ReportId { get; set; }
public virtual Report Report { get; set; }
public int UserId { get; set; }
public virtual UserProfile User { get; set; }
}
public class Comment {
[Key]
public int Id { get; set; }
public DateTime CreationDate { get; set; }
public string Text { get; set; }
public int ReportId { get; set; }
public virtual Report Report { get; set; }
public int UserId { get; set; }
public virtual UserProfile User { get; set; }
}
public class UserProfile {
[Key]
public int Id { get; set; }
public string Stamnummer { get; set; }
public string Leverancier { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Report> Reports { get; set; }
public virtual ICollection<Photo> Photos { get; set; }
}
In order to be certain, we need to see how you have configured your relationships using the model builder in the OnModelCreating method. Based on the error message you have provided, it appears that you have relationships configured so that one of your entities is configured for cascade on delete from two or more other entities.
As an example (this may not be the case, but rather just a means of describing the problem):
User has a one-to-many relationship with Comments
User has a one-to-many relationship with Reports
Report has a one-to-many relationship with Comments
Comment is configured so that a User is required
Comment is configured so that a Report is required
Report is configured so that a User is required
Any one-to-many relationship where the entity one side of the relationship is required is going to have cascade on delete configured by default. In this scenario, if a User were deleted it would trigger a cascade to both Reports and Comments. Each Report would also cause a cascade on Comments.
The solution is to disable cascading deletes for one of the relationships. You can find a similar question to yours here describing what I mentioned above.

EF Code first : set optional one to one relationship with data annotation

I've the following situation I try to solve : I've 2 tables, a Course table with some fields and a CourseDescription table which is optional (so Course may have a CourseDescription but CourseDescription must have a Course). I'm trying to set this up. So far, here's what I have :
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public virtual CourseDescription CourseDescription { get; set; }
}
public class CourseDescription
{
[Key, ForeignKey("Course")]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
public int CoursesID { get; set; }
[ForeignKey("CoursesID")]
public Course Course { get; set; }
}
This "works" meaning that EF doesn't complains about my model but the relation is not properly done because EF associate the PK of CourseDescription with the PK of Course. In my database, this is not the case (ex : CourseDescription.ID=1 is associated with CourseDescription.CoursesID=3, not 1).
Is there a way to fix that with data annotation ? I know I can use the fluent API but I don't want to override the model building just for that (unless there's no other way).
Thanks
Well, I think you have two choices:
Configure an one to many relationship
If you want to map the FK of the relationship between Course and CourseDescription, and you don't want to declare that FK property as Key of the CourseDescription entity, then, you don't have other choice that configure an one-to-many relationship. In that case your model would be like this:
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<CourseDescription> CourseDescriptions { get; set;}
}
public class CourseDescription
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
[ForeignKey("Course")]
public int CourseID { get; set; }
public Course Course { get; set; }
}
Configure an one-to-one relationship but not map the FK of the
relationship
The only way that EF lets you map the FK in an one-to-one relationship is when the FK is declared as a PK too, so if you want to have diferent Ids in both entities and you want to stablish an one-to-one relationship, then you could do something like this:
public class Course
{
[Key, Column("Key_Course")]
public int ID { get; set; }
public string Name { get; set; }
public CourseDescription CourseDescription { get; set;}
}
public class CourseDescription
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
[Required]
public Course Course { get; set; }
}
And work with the navigations properties.
It looks like you should not use ForeignKey attribute for ID property of CourseDescription class as you don't want to have an association between primary keys. Try to remove it.
Edit: It looks like I misunderstood the question previous time.
You can have your CourseDescription this way.
public class CourseDescription
{
[Key, ForeignKey("Course")]
public int ID { get; set; }
public string Description { get; set; }
public string PreRequis { get; set; }
public Course Course { get; set; }
}
In this case you don't need to have CoursesID field. Entities will be connected by primary keys.

E.F 6.0 Code first One to One Navigation Property Exception

I am issuing a very strange scenario using Code first with existing database and asp.net identity entity framework. I have a simple userprofile model
[Table("CSUserProfile")]
public partial class UserProfile
{
[Key]
public string Id { get; set; }
[Required]
[Display(Name = "FirstName")]
public string FirstName { get; set; }
[Required]
[Display(Name = "LastName")]
public string LastName { get; set; }
[Required]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
[Required]
[Display(Name = "Location")]
public string Location { get; set; }
[Required]
[Display(Name = "HomeTown")]
public string Hometown { get; set; }
public byte[] BlobData { get; set; }
[ForeignKey("fPersonLinkGID")]
public virtual List<ProfilePic> ProfilePic { get; set; }
}
and an image profile pic
[Table("CSProfilePic")]
public partial class ProfilePic
{
[Key]
public Guid? GID { get; set; }
public string fPersonLinkGID { get; set; }
public byte[] BlobData { get; set; }
}
the foreign key is the fPersonLinkGID. everything works fine but my problem is that if i want an one-to-one relation between the userprofile and the image like this
public virtual ProfilePic ProfilePic { get; set; }
(which is the correct scenario) I am getting this strange exception :
The ForeignKeyAttribute on property 'ProfilePic' on type 'eUni.Model.Application.UserProfile' is not valid. The foreign key name 'fPersonLinkGID' was not found on the dependent type 'eUni.Model.Application.UserProfile'. The Name value should be a comma separated list of foreign key property names.
I can not understand why I am getting that exception
You could read this answer. It introduces how to configure one to one relationship by HasRequired and WithOptional.
As for me, I will create one to one relationship by following way.
public class Store {
[Key]
public long Id { get; set; }
public virtual Item TheItem { get; set; }
// ....
}
public class Item {
// It is FK, and also PK.
[Key, ForeignKey("TheStore")]
public long Id { get; set; }
// The same string in the ForeignKey attribute. Ex: ForeignKey("TheStore")
public virtual Store TheStore { get; set; }
// ....
}

Code-first Entity Framework - Multiple Foreign Keys For the Same Table

I have a Holiday table and a User table.
The Holiday table has columns RequesterID and AuthorisedByID, which both link to the primary key of the User table.
This is my Holiday model:
public class Holiday
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid HolidayId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
public Guid RequesterId { get; set; }
public Guid? AuthorisedById { get; set; }
}
I am unable to declare the AuthorisedByID as a foreign key in the User table just like I think I did with RequesterId column.
I wonder if you can give me some hints on how to resolve.
Thanks.
Code first is not able to match up the properties in the two classes on its own.
To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties.
[ForeignKey("RequesterUser")]
public Guid RequesterId { get; set; }
[ForeignKey("AuthorisedUser")]
public Guid AuthorisedById { get; set; }
[InverseProperty("RequesterHoliday")]
public virtual User RequesterUser{ get; set; }
[InverseProperty("AuthorisedHoliday")]
public virtual User AuthorisedUser{ get; set; }
public List<Holiday> RequesterHoliday { get; set; }
public List<Holiday> AuthorisedHoliday{ get; set; }