locked
Problem with EntityFramework Navigation Property saving relational data concept -- RRS feed

  • Question

  • User-215451226 posted

    Hello. I am a little stuck on a concept, so asking this question.

    In my project entities, I have -

    NewsCategory entity -

    public class NewsCategory
        {
            [Key]
            public int Id { get; set; }
    
            public int CategoryName { get; set; }
    
            public string CategoryInfo { get; set; }
        }

    NewsTopic entity -

    public class NewsTopic
        {
            [Key]
            public int Id { get; set; }
    
            [Required]
            public string TopicId { get; set; }
    
            [Required]
            public string TopicName { get; set; }
    
            [MaxLength(1000)]
            public string TopicInfo { get; set; }
    
            [Required]
            public DateTime IssueStartDate { get; set; }
    
            [Required]
            public DateTime IssueCloseDate { get; set; }
    
            public NewsCategory NewsCategory { get; set; }
        }

    As you can see, NewsTopic contains a relationship member with NewsCategory. I applied CF entity migration to create my DB and tables. The NewsTopics table
    has a column NewsCategory_Id. Now suppose I am trying to save data into this table from a front end Angular app. I have a databound select list for
    news categories and other textboxes etc. I tried to send data to NewsTopicController method and tried two variations - sending id value, sending name value for selected
    category from select list. Neither worked. Here are my C# code blocks (uow is for unitofwork I used) -

    In controller class -

    [Route("api/NewsTopic/CreateNewsTopic")]
            [HttpPost]
            [AllowAnonymous]
            public string CreateNewsTopic(NewsTopic nObj)
            {
                try
                {
                    nObj.IssueStartDate = DateTime.Now;
                    var status=uow.NewsTopicRepo.AddNewsTopic(nObj);
                    uow.Complete();
                    _db.SaveChanges();
                    return status;
                }
                catch(Exception exp)
                {
                    throw exp.InnerException;
                }
            }

    Method implementation in repository class -

    public string AddNewsTopic(NewsTopic objNT)
            {
                try
                {
                    if(_entities.NewsTopics.Any(nt=>nt.TopicId==objNT.TopicId))
                    {
                        return "Duplicate Topic ID";
                    }
                    else
                    {
                        _entities.NewsTopics.Add(objNT);
                        _entities.SaveChanges();
                        return "Success";
                    }
                }
                catch(Exception exp)
                {
                    throw exp.InnerException;
                }
                
            }

    The other fields are saved to DB but not the NewsCategory_Id navigation field. It remains null. Why? How can I edit/update or improve my entity relationship structure?
    What mistake I made?? What changes do I have to implement and where? Or is there any quick fix solution I can apply to front end that would do it?
    Give me some ideas please. Much needed!

    Thanks You All,

    Monday, August 19, 2019 4:20 PM

All replies

  • User1520731567 posted

    Hi PGChoudhury,

    According to your model,I find you may want to use one to one entity,you could refer to this tutorial,

    for example:

    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
    
        public virtual StudentAddress Address { get; set; }//navigation property
    }
         
    public class StudentAddress 
    {
        [ForeignKey("Student")]
        public int StudentAddressId { get; set; }
            
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public int Zipcode { get; set; }
        ...
    
        public virtual Student Student { get; set; }//navigation property
    }

    And if you want to implement CRUD on this one to one entity,I suggest you could create a scaffold item which is a standard template in Microsoft:

    You could follow the steps below:
     
    Right click on Controllers -> Choose Add -> Choose 'MVC5 Controller with views, using Entity Framework', then Add-> Choose the Model(NewsCategory or NewsTopic) you want to add CRUD to in 'Model class', then Add -> The controller with CRUD function is created.
     
    Then you will find CRUD related pages are automatically generated.

    Best Regards.

    Yuki Tao 

    Tuesday, August 20, 2019 7:22 AM
  • User-215451226 posted

    Hi @YukiTao,

    Just saw this, I was ill as you already know. I appreciate your effort;
    But could you just remodel your answer with relevance to my scenario, like NewsCategory and NewsTopics so that I can visualize it.
    Also, can you just show me a diagram or screen shot of sorts what gets created in the database(the tables, with their columns and types) when you apply migration on that.

    So I can compare with mine,

    That would help me,

    Thanks,

    Thursday, August 29, 2019 7:14 AM
  • User283571144 posted

    Hi PGChoudhury,

    Could you please tell me the relationship between the NewsCategory and NewsTopic?

    Does one NewsTopic could has multiple NewsCategory  or not? We should create the data model based on relationship.  

    Best Regards,

    Brando

    Tuesday, September 3, 2019 6:50 AM