Data in the table using data from the related table



  • Good afternoon.

    There is a database of two tables. The tables are structured through Entity Framework Code First. The structure is as follows:

    public class FederationMembers
    {
        public Guid ID { get; set; }
        [Required MaxLength(10)]
        public string ISO_Code { get; set; }
        [Required MaxLength(100)]
        public string Title { get; set; }
        [Required MaxLength(3)]
        public string Number { get; set; }
    }
    

    public class LawEnforcement
    {
    public Guid ID { get; set; }
    [Required MaxLength(200)]
    public string Title { get; set; }
    [MaxLength(300)]
    public string Address { get; set; }
    public FederationMembers SubjectOfFederation { get; set; }
    }

    Table FederationMembers is to be completed at the initialization stage of the OBD.
    I'm trying to record the LawEnforcement table, and I'm getting a mistake that the system is trying to add PrimeryKey to the FederationMembers table, which already exists. There's a code in SQL.

    INSERT [tbl].[FederationMembers]([ID], [ISO_Code], [Title], [NUMBER])
    VALUES (@0, @1, @2, @3)

    Listing code, LawEnforcement below

    Context context = new Context();
    Models.LawEnforcement lea = new Models.LawEnforcement();
    lea.ID = Guid.NewGuid();
    lea.Title = Request["lea_title"];
    lea.Address = Request["address"];
    lea.SubjectOfFederation = repo.FederationMembers.Where(c => c.ID.ToString() == Request["lea_fm"]).First();
    context.LawEnforcement.Add(lea);
    context.SaveChanges();

    Why is the system trying to add a record to FederationMembers when I try to add a record to LawEnforcement?



  • Try to:

    1. Add another class characteristic LawEnforcement:

      public Guid SubjectOfFederationID { get; set; }
      
    2. Make your properties. SubjectOfFederation Virtual:

      public virtual FederationMembers SubjectOfFederation { get; set; }
      
    3. Add as follows:

      using(Context context = new Context())
      {
          var federationMember = context.FederationMembers.Where(c => c.ID.ToString() == Request["lea_fm"]).First();
          if (federationMember != null)
          {
              var lea = new Models.LawEnforcement()
              {
                  ID = Guid.NewGuid(),
                  Title = Request["lea_title"],
                  Address = Request["address"],
                  SubjectOfFederationID = federationMember.ID
              };
              context.LawEnforcement.Add(lea);
              context.SaveChanges();
          }
      }
      

    Upon addition and modification of class properties, changes in the database should be applied.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2