D
D
Dmitry Gavrilenko2016-11-02 14:41:46
.NET
Dmitry Gavrilenko, 2016-11-02 14:41:46

Entity Framework not saving related data?

Friends. I have a bathert from EF Core. I'm starting to get angry.
I have 2 entities

public class Realtor
{
        public Realtor()
        {
            Guid = Guid.NewGuid();
            Registration = DateTime.Now;
        }
        public int Id { get; set; }
        public Guid Guid { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime Registration { get; set; }
        public int SubdivId { get; set; }
        public Subdiv Subdiv { get; set; }
}

public class Subdiv
{
        public Subdiv()
        {
            Created = DateTime.Now;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Created { get; set; }
        public List<Realtor> Realtors { get; set; }
}

If you understand, then you see the connection One to Many ( Subdiv => Realtor )
Implemented WebAPI on ASP.NET Core.
For each entity there are corresponding Add, Del, Change, Get methods.
So. I added one Subdiv (TOSTER TM) and got its ID.
Next, I add one Realtor and stuff the newly created TOSTER TM found by ID into the Subdiv property (see screenshot).
vi_EurGNGOo.jpg
The screenshot shows that Break Point is after context.SaveChanges(). This means that the object is already in the database, has its own Id, etc... The main thing I want to show is that Realtor.Subdiv has an object of type Subdiv. Even SubdivId is specified. OK.
Next, I try to extract and base the newly added Realtor.
Using the API, I pass the ID and look for the object in the database. To great happiness - the object is found! (see screenshot)
gQqoSAdIWms.jpg
But please pay attention to the field Subdiv ... NULL!!!!!!
OK. We have feedback. We get the Subdiv object, which is missing in the Realtor above, and look at its List BJ8yVsPrRSQ.jpg
NULL!!!!!!!!!
5483483.jpg
Okay ..
By the way, I just didn’t try
1 - mark the necessary fields with the [Key] and [ForeingKey] attributes
2 - described such things in the OnModelCreating method
modelBuilder.Entity<Realtor>(real => {
        real.HasOne(r => r.Subdiv)
        .WithMany(s => s.Realtors)
        .HasForeignKey(r => r.SubdivId);
});

3 - something else ..
And nothing helped. Please help me to solve this problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Zhidkov, 2016-11-02
@Maddox

include() ?
More precisely, like this:

context.Subdivs.Include(i=>i.Realtor).First(s=>s.Id == id):

R
Roman, 2016-11-02
@yarosroman

www.entityframeworktutorial.net everything is here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question