Quantcast
Channel: CodeProject Latest postings for ASP.NET
Viewing all articles
Browse latest Browse all 3938

How to fill Foreign Key in a relational database when creating a new row?

$
0
0
I have a model as follows:

[Key]publicint pmId { get; set; }
[Required]publicint pmNumber { get; set; }
[Required]
[MaxLength(50)]publicstring costCenter { get; set; }
[Required]
[MaxLength(15)]publicstring serviceType { get; set; }
[Required]
[MaxLength(50)]publicstring destination { get; set; }
[Required]
[MaxLength(50)]publicstring workCenter { get; set; }
[Required]public DateTime creationDate { get; set; }
[Display]
[Required]public DateTime startDate { get; set; }
[Required]public DateTime endDate { get; set; }
[Required]
[MaxLength(100)]publicstring mainFileName { get; set; }public DateTime? returnDate { get; set; }publicstring? status { get; set; }
[MaxLength(100)]publicstring? fileName { get; set; }publicint? uploader { get; set; }publicbool? isDownloaded { get; set; } = false;//Navigation propertypublicvirtual AppUser user { get; set; }//Navigation propertypublic PM()
{

}


The Foreign Key is id which is Primary Key of the EF Core Identity table. In a form, I need to insert a new row in PM table. I can fill all necessary columns using the following code:

var inputElements = new PM()
            {
                pmNumber = Convert.ToInt32(adminModel.pmNumber),
                costCenter = adminModel.costCenter,
                serviceType = adminModel.serviceType,
                destination = adminModel.destination,
                workCenter = adminModel.workCenter,
                creationDate = DateTime.Now,
                startDate = DateTime.Now,
                endDate = DateTime.Now,
                mainFileName = newFileName
            };


But, because of relational nature of my tables, I need to specify userId when creating a new row in PM table. How can I set Foreign Key? I can detect userId using Session object but I don't know how to insert it in the table.

Viewing all articles
Browse latest Browse all 3938

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>