简体   繁体   中英

Problem getting the whole object from Entity Framework when requesting via API methods

I have a problem with the API requests. I'm trying to get the whole object from the server to the client, it is retrieved, but without some fields.

This is what it should get for job object , but the problem is that it is returned with null values: see photo-1

I mention that adult has that specific job: see photo-2

I tried also to rebuild the migrations, database or also to add a DbSet for everything that the object has, but nothing.

Having this problem, I can't update or remove the object.

What should it be?

You need to add the entity class definitions for your Adult and Job/JobTitle classes. The cause is likely either that you don't have a many-to-one relationship properly mapped between the two, or you have disabled lazy loading and have done something like:

public class Adult
{
    // ....


    public Job JobTitle { get; set; } = new Job();
}

Which would see EF load an Adult but have an initialized empty job title. You should only initialize one-to-many collections.

The mapping can be done either by Attribute, EntityTypeConfiguration, or modelBuilder in the DbContext OnModelCreating. Basing assumptions on your model it should look something like:

public class Adult
{
    [Key]
    public int Id { get; set; }
    // Other properties...

    [ForeignKey("JobTitleIdJob")]
    public virtual Job JobTitle { get; set; }
}

public class Job
{
    [Key]
    public int IdJob { get; set; }
    public string JobTitle { get; set; }
}

The FK on JobTitle above uses a shadow property, alternatively you can define the FK field in Adult as well, but the FK relationship needs to be explicitly mapped since the column name does not conform to the naming convention of the type. (Ie JobId or Job_Id)

If your relationships are set up properly then eager loading the job title can be done when loading the Adult(s).

var adult = context.Adults
    .Include(x => x.Job)
    .Single(x => x.Id == adultId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM