简体   繁体   中英

How do I configure one-to-one relationship in EF Core if one of entities does not reference the other one?

So the problem is that I have two entities, one of which is in another library, so I can't modify it. And my model contains (has a relationship) this model from another library. I want to configure one-to-one relationship between them.

public class UserInfo
{      
    public User User { get; set; } 

    public bool IsVerified { get; set; }

    public DateTime? UtcVerifyDate { get; set; }
}

// model from library
public class User : IEquatable<User>
{
    public int Id { get; set; }

    public bool IsBot { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Username { get; set; }

    public string LanguageCode { get; set; }
}

So I googled the question and even searched on stackoverflow and even found same question but there's no answer that would satisfy me. Because what I need is one-to-one relationship without adding a UserInfo property to the User class, because I can't do that since this class is from another library. I tried different approaches but none have worked, so I think I won't describe all of them here because it would require a big amount of text.

I found the solution:

Place this

blder.Entity<UserInfo>()
     .HasOne(i => i.User)
     .WithOne();

blder.Entity<UserInfo>()
     .HasKey(i => i.UserId);

Inside your OnModelCreating method in the dbcontext class (don't forget to call base.OnModelCreating)

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