0

我使用的是 EF5 Code First 并且延迟加载被禁用。我有以下代码:

//Model
public class Task
{
    public Guid Id {get; set;}
    //other properties that are not relevant here
    public Guid CreatorId {get; set;}
    public User Creator {get; set;}
    public Guid? OwnerId {get; set;}
    public User Owner {get; set;}
}

//Model
public class User
{
    public Guid Id { get; set; }
    //other properties that are not relevant here
    public string UserName { get; set; }

    public IList<Task> TasksCreated { get; set; }
    public IList<Task> TasksOwned { get; set; }
}

//Configuration for Task
public class TaskConfiguration : EntityTypeConfiguration<Task>
{
    public TaskConfiguration()
    {           
        HasRequired(task => task.Creator)
            .WithMany(creator => creator.TasksCreated)
            .HasForeignKey(task => task.CreatorId)
            .WillCascadeOnDelete(false);

        HasOptional(task => task.Owner)
            .WithMany(owner => owner.TasksOwned)
            .HasForeignKey(task => task.OwnerId)
            .WillCascadeOnDelete(false);
    }
}

当我查询任务时,所有数据都按预期返回。当我使用以下查询查询用户时,所有者或创建者的任务属性为空。空值分配给与我正在查询的用户不匹配的任何属性。因此,如果 User2 是 User1 任务的所有者,则 User2 的 ID 将返回,但 Owner 属性将为空。这是查询:

var db = new MyContext();
var user = db.Users
             .Include("TasksCreated")
             .Include("TasksOwned")
             .SingleOrDefault(u => u.UserName.Equals("user1", StringComparison.OrdinalIgnoreCase));

我不确定是否缺少另一个步骤,或者我是否没有正确配置任务-用户关系。任何帮助表示赞赏。

4

1 回答 1

0

我试试你的代码,它运行。唯一的区别是我添加的上下文的构造函数:

public class TestEFContext : DbContext {
    public IDbSet<User> us { get; set; }
    public IDbSet<Task> ts { get; set; }

    public TestEFContext(String cs)
        : base(cs) {
        Database.SetInitializer<TestEFContext>(new DropCreateDatabaseAlways<TestEFContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        Configuration.LazyLoadingEnabled = false;

        modelBuilder.Configurations.Add(new TaskConfiguration());            
    }
}

从这里开始:

class Program {
    static void Main(String[] args) {
        String cs = @"Data Source=ALIASTVALK;Initial Catalog=TestEF;Integrated Security=True; MultipleActiveResultSets=True";
        using (TestEFContext c = new TestEFContext(cs)) {
            User u1 = new User {
                Id = Guid.NewGuid(),
                UserName = "u1"
            };
            User u2 = new User {
                Id = Guid.NewGuid(),
                UserName = "u2"
            };
            c.us.Add(u1);
            c.us.Add(u2);
            Task t = new Task {
                Id = Guid.NewGuid(),
                Creator = u1,
                Owner = u1
            };                
            c.ts.Add(t);
            t = new Task {
                Id = Guid.NewGuid(),
                Creator = u2,
                Owner = u1
            };
            c.ts.Add(t);
            c.SaveChanges();                
        }

        using (TestEFContext c = new TestEFContext(cs)) {
            var user = c.us
             .Include("TasksCreated")
             .Include("TasksOwned")
             .SingleOrDefault(u => u.UserName.Equals("u1", StringComparison.OrdinalIgnoreCase));
            foreach (Task t in user.TasksCreated) {
                Console.WriteLine(t.Id);
            }
            Console.WriteLine("-----");
            foreach (Task t in user.TasksOwned) {
                Console.WriteLine(t.Id);
            }
        }
    }
}

按预期显示:

a415c8c6-6b0a-4e1b-a42f-cd4230cf4d4a
-----
a415c8c6-6b0a-4e1b-a42f-cd4230cf4d4a
a2e9c527-d8cb-4db7-8879-7febb1c30a07
Appuyez sur une touche pour continuer...

版本 ========== ==========

以下代码也运行:

using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;

namespace testef {
    //Model
    public class Task {
        public Guid Id { get; set; }
        //other properties that are not relevant here
        public String ShortDescription { get; set; }
        public Guid CreatorId { get; set; }
        public User Creator { get; set; }
        public Guid? OwnerId { get; set; }
        public User Owner { get; set; }
    }

    //Model
    public class User {
        public Guid Id { get; set; }
        //other properties that are not relevant here
        public string UserName { get; set; }

        public IList<Task> TasksCreated { get; set; }
        public IList<Task> TasksOwned { get; set; }
    }

    //Configuration for Task
    public class TaskConfiguration : EntityTypeConfiguration<Task> {
        public TaskConfiguration() {
            HasRequired(task => task.Creator)
                .WithMany(creator => creator.TasksCreated)
                .HasForeignKey(task => task.CreatorId)
                .WillCascadeOnDelete(false);

            HasOptional(task => task.Owner)
                .WithMany(owner => owner.TasksOwned)
                .HasForeignKey(task => task.OwnerId)
                .WillCascadeOnDelete(false);
        }
    }
    public class TestEFContext : DbContext {
        public IDbSet<User> us { get; set; }
        public IDbSet<Task> ts { get; set; }

        public TestEFContext(String cs)
            : base(cs) {
            Database.SetInitializer<TestEFContext>(new DropCreateDatabaseAlways<TestEFContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);

            Configuration.LazyLoadingEnabled = false;

            modelBuilder.Configurations.Add(new TaskConfiguration());            
        }
    }

    class Program {
        static void Main(String[] args) {
            String cs = @"Data Source=ALIASTVALK;Initial Catalog=TestEF;Integrated Security=True; MultipleActiveResultSets=True";
            using (TestEFContext c = new TestEFContext(cs)) {
                User u1 = new User {
                    Id = Guid.NewGuid(),
                    UserName = "u1"
                };
                User u2 = new User {
                    Id = Guid.NewGuid(),
                    UserName = "u2"
                };
                c.us.Add(u1);
                c.us.Add(u2);
                Task t = new Task {
                    Id = Guid.NewGuid(),
                    ShortDescription = "t1",
                    Creator = u1,
                    Owner = u1
                };
                c.ts.Add(t);
                t = new Task {
                    Id = Guid.NewGuid(),
                    ShortDescription = "t2",
                    Creator = u2,
                    Owner = u1
                };
                c.ts.Add(t);
                c.SaveChanges();
            }

            using (TestEFContext c = new TestEFContext(cs)) {
                var user = c.us
                 .Include("TasksCreated")
                 .Include("TasksOwned")
                 .SingleOrDefault(u => u.UserName.Equals("u1", StringComparison.OrdinalIgnoreCase));
                foreach (Task t in user.TasksCreated) {
                    Console.WriteLine("{0} - {1} is owned by {2}, was created by {3} ", t.ShortDescription, t.Id, t.OwnerId, t.CreatorId);
                }
                Console.WriteLine("-----");

                foreach (Task t in user.TasksOwned) {
                    Console.WriteLine("{0} - {1} is owned by {2}, was created by {3} ", t.ShortDescription, t.Id, t.OwnerId, t.CreatorId);
                }
            }
        }
    }
}
于 2013-03-21T10:31:57.493 回答