.NET核心实体框架获取多个表

时间:2017-03-29 00:02:27

标签: c# .net entity-framework

Sql Tables Here

public partial class Users
{
    public Users()
    {
        UsersRelationFollower = new HashSet<UsersRelation>();
        UsersRelationFollowing = new HashSet<UsersRelation>();
        Vote = new HashSet<Vote>();
        VoteRating = new HashSet<VoteRating>();
    }

    public string Id { get; set; }
    public string UserType { get; set; }
    public string UserName { get; set; }
    public string Mail { get; set; }
    public string ImageUrl { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime? ModifyDate { get; set; }
    public bool State { get; set; }


    public virtual UserPasswords UserPasswords { get; set; }
    public virtual CorporateProperty CorporateProperty { get; set; }
    public virtual UserProperty UserProperty { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollower { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollowing { get; set; }
    public virtual ICollection<Vote> Vote { get; set; }
    public virtual ICollection<VoteRating> VoteRating { get; set; }
}

public partial class UserProperty
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDay { get; set; }
    public string Gender { get; set; }
    public string Locale { get; set; }
    public string PhoneNumber { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}

public partial class CorporateProperty
{
    public string Id { get; set; }
    public string OrganisationName { get; set; }
    public string Website { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}

UserControllerClass

// GET: api/Users/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetUsers([FromRoute] string id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);

        if (users == null)
        {
            return NotFound();
        }
        return Ok(users);
    }

我的问题正是这样;用户信息即将发布,但密码和属性表信息不会出现。

如何修改以下行解决了我的问题?

var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);

1 个答案:

答案 0 :(得分:0)

根据您的代码,这也可以保护您的CorporateProperty&amp; UseProperty对象等

var user = await _context.Users.Include(user => user.UserProperty).Include
(user => user.CorporateProperty).SingleOrDefaultAsync(user => user.Id == id);

延迟加载还没有存在,所以你现在可以暂时加载。

很惊讶你没有使用Identity,因为所有这些都会被照顾你,特别是密码...希望你不是为了自己的哈希而滚动...

只需添加您需要的自定义类/集合对象。

您也可以查看此链接 https://docs.microsoft.com/en-us/ef/core/querying/related-data