0

In a project that involves an Asp.Net Core API and Entity Framework, I have the following entities:

public class A
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; private set; }

    [Required] public string Name { get; set; }

    [Required] public B MyObj { get; set; }
}

public class B
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; private set; }
}

My API has this model, which represents a POST request body for the creation of a new A:

public class A_Post
{
    public string Name { get; set; }

    public string Obj_Id { get; set; }
}

Here, Obj_Id refers to the Id of the B instance that I want A.MyObj to have as its value.

What I want to do is add a method to A that creates an instance of A from an instance of A_Post. Something like this:

public static A CreateFromPost(A_Post post)
{
    var entity = new A();
    entity.Name = post.Name;
    // post.Obj_Id is accessible here, but cannot set entity.MyObj
    return entity;
}

However, I'm not sure how to go from having the Obj_Id to having the entity it corresponds to, without getting it from the context. Is there a way to do this? Or will I have to set MyObj somewhere else in the program, where the context can be accessed?

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53

0 Answers0