如何模拟用户和 post 地址以通过邮政编码查找城市?

How to model users and post addresses to find the city by zip code?

我希望能够根据用户的邮政编码加载城市作为用户的相关数据。我知道不建议使用邮政编码本身作为键,因为它可能会在未来发生变化。

我有一些型号:

public class ApplicationUser : IdentityUser<Guid>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PostAddress { get; set; } // Street, c/o., apartment number, etc.
    public string Zip { get; set; }
    // More properties ...
}

public class City
{
    public Guid Id { get; set; }
    public string Zip { get; set; }
    public string Name { get; set; }
}

目前,在获取用户的邮政编码后,我在单独的查询中获取城市。

最后,我想这样查询:

var User = await db.Users.Where(u => u.Id == id)
    .Include(c => c.City)
    .FirstOrDefaultAsync();

...但我不知道我应该如何 link 这两个表。

尝试将 [ForeignKey] 属性应用于导航 属性 并将 [Key] 属性应用于 Id 属性 City class 使其成为密钥 属性:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class ApplicationUser : IdentityUser<Guid>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PostAddress { get; set; } // Street, c/o., apartment number, etc.

    public int CityId { get; set; }
    [ForeignKey("CityId")]
    public City City { get; set; }
}

public class City
{
    [Key]
    public Guid Id { get; set; }
    public string Zip { get; set; }
    public string Name { get; set; }
}

有关其他信息,请参阅 Data Annotations - ForeignKey Attribute in EF 6 & EF Core