EF一对多检索外键但不检索对象

时间:2015-11-27 11:43:41

标签: c# entity-framework

有两个班级

事件

public class Event 
{

    public Guid? UserID { get; set; }

    [ForeignKey("UserID")]
    public virtual User User { get; set; }
...

用户

 public class User
{
    public Guid UserId { get; set; }
    // Not used in this example, but just thought they might be related to problem
    private List<Event> _attendedEvents;
    public virtual ICollection<Event> AttendedEvents 
    {
        get { return _attendedEvents ?? (_attendedEvents = new List<Event>()); }
        set {
            if (value == null)
                _attendedEvents = new List<Event>();
            else
                _attendedEvents = new List<Event>(value);
        } 
    }
    public virtual ICollection<Event> HostedEvents { get; set; }
...

EventConfiguration

HasOptional<User>(s => s.User)
    .WithMany(s => s.HostedEvents)
    .HasForeignKey(s => s.UserID);
  1. 我想做的事是
  2. 将用户添加到存储库
  3. 将事件(其中包含相同的用户)添加到存储库
  4. 保存更改
  5. 从存储库中检索事件
  6. 一切都有效,除非我检索事件回来时它有空用户,但UserId有效并指向我之前创建的用户。

    以下是我正在做的事情

    // Creates just the User object with specified UserName
    var user = ObjectHelpers.CreateUser("ServiceTestUser");
    
    // Adds to Repository + Saves Changes
    _client.AddUser(user);
    
    // Find it again to have generated Id and kind of test if it was added
    user = _client.FindUserByEmail(user.Email);
    
    // Create Event object and assign specified user object to it
    // At this point @event has User set to above one and UserID null
                var @event = ObjectHelpers.CreateEvent(user);
    
    // Attach User from Event + Add Event to repository + Save Changes
    _client.AddEvent(@event);
    
    // Get it back to Check if everything went fine
    // At this point @event has User set to null and valid UserID
    @event = _client.GetEventByTitle(@event.EventTitle);
    

1 个答案:

答案 0 :(得分:2)

默认情况下,EF不会读取相关实体。这种行为非常有用。如果没有,每当你试图从数据库中读取一个实体时,你就会读到那个实体,以及所有可能非常大的相关实体树。

您必须阅读已实体化的实体:

  • 明确地使用.Include()
  • 或隐式地,通过使用延迟加载,这意味着访问导航属性,但DbContext尚未被处理

Include()的示例:

DbCtx.Events.First(ev => ev.Title == "title").Include(ev => ev.User);

有关包含相关实体的详细信息,请参阅:Loading Related Entities