【问题标题】:Setting up optional:required relationship Entity Framework - fluent API设置可选:必需的关系实体框架 - 流式 API
【发布时间】:2011-11-24 09:20:56
【问题描述】:

我有一个 USER - PROFILE 关系,用户可以(可选)关联一个配置文件。 在数据库中,PROFILES 表有一个指向 USERS 表的外键(外键可以为空)。

我想使用 EF fluent API 进行设置。我设法做到了,一切正常,但问题是我不能将配置文件中的 FK 作为类中的属性。

所以在数据库中我有:

[USERS]
ID uniqueidentifier PK not null

[PROFILES]
ID uniqueidentifier PK not null
USERID uniqueidentifer FK null

在我的代码中:

public class User { public virtual Profile { get; set; } }
public class Profile { public virtual User { get; set; } }

请注意,DB 中的列名不符合 EF 命名约定。

我可以如下配置EF:

HasOptional(u => u.Profile).WithRequired(p => p.User).Map(m => m.MapKey("USERID")).WillCascadeOnDelete();

或者反过来:

HasRequired(p => p.User).WithOptional(u => u.Profile).Map(m => m.MapKey("USERID")).WillCascadeOnDelete();

在这种情况下,我真的需要使用 MapKey 映射 FK(因为 EF 使用的命名约定),这似乎是我无法在模型中添加 FK 的问题。

所以我不能拥有:

public class Profile { public virtual User { get; set; } public Guid? UsreId { get; set; } }

任何人都知道我该如何做到这一点?

编辑 问题的根源在于,如果我不使用 .Map(m => m.MapKey("USERID")) 方法,那么约定会破坏这种关系(它期望 FK 是 User_Id),这基本上就像在没有使用它的情况下使用它任何参数。如果我使用 .Map(m => m.MapKey("USERID")) 方法,那么它表示我已经将 UserId 作为模型中的属性(来自内联帮助:配置关系以使用外键属性) 未在对象模型中公开。可以通过指定配置操作来自定义列和表。如果指定了空配置操作,则将生成列名称按照惯例)。

无赖...

EDIT 2设法以某种方式修复它(基本上是另一种方法)。 将表格更改为:

[USERS]
ID uniqueidentifier PK not null

[PROFILES]
-- ID uniqueidentifier PK not null (removed the PK)
USERID uniqueidentifer PK not null, FK not null -- (the PK is also the FK)

在运行 SQL 分析器并查看那里运行的查询后,我最终来到了这里。 根据 USERID 查询每个用户的选项 PROFILE。 were 子句类似于:

SELECT *
FROM PROFILES
WHERE ID = @userId -- ID was the PK

所以我发现在这种情况下,来自 PROFILES 表的 PK 也必须是 FK,并且映射可以保持简单:

HasOptional(u => u.Profile).WithRequired(p => p.User);

或者在另一端

HasRequired(p => p.User).WithOptional(u => u.Profile);

这个很有帮助:http://msdn.microsoft.com/en-us/library/hh295843%28v=vs.103%29.aspx

干杯!

【问题讨论】:

    标签: c#-4.0 entity-framework-4.1 code-first


    【解决方案1】:

    您需要专注于正确映射实体本身,然后关系才会起作用。关于键的约定是这样的:

    1. 如果实体有一个名为 Id 的属性,它将用作键
    2. 如果有 EntityId(例如 UserId)属性,那么这就是关键
    3. 您需要指定 key 属性是什么

    至于key属性对应数据库中的哪一列,可以通过Property()和HasColumnName()方法指定。

    完成此操作后,您不必担心在关系映射中映射键(至少在您的情况下是一对一映射)。

    对于关系映射,您不必同时从用户和配置文件定义关系。一旦您以一种方式定义关系,就会推断出另一种方式。这也使您的代码保持干净。

    下面的代码应该可以帮助你理解整个事情。

    class Program
    {
        static void Main(string[] args)
        {
            // replace your connection string here
            using (var userContext = new UserContext("UserProfile"))
            {
                var u = new User { UserId = Guid.NewGuid(), Name = "John", Profile = new Profile() { ProfileId = Guid.NewGuid(), SomeValue = "x" } };
    
                userContext.Users.Add(u);
                userContext.SaveChanges();
    
                var users = userContext.Users.ToList();
    
                foreach (var user in users)
                {
                    Console.WriteLine(user.Name);
                    if (user.Profile != null)
                    {
                        Console.WriteLine(user.Profile.ProfileId);
                    }
                }
    
                var profiles = userContext.Profiles.Where(p => p.User.Name == "John").ToList();
            }
        }
    }
    
    public class UserContext : DbContext
    {
        public UserContext(string connectionString)
            : base(connectionString)
        {
        }
    
        public DbSet<User> Users { get; set; }
    
        public DbSet<Profile> Profiles { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<User>().Property(u => u.UserId).HasColumnName("ID");
            modelBuilder.Entity<Profile>().Property(p => p.ProfileId).HasColumnName("ID");
    
            modelBuilder.Entity<User>().HasOptional(u => u.Profile).WithRequired(p => p.User);
        }
    }
    
    public class User
    {
        public Guid UserId { get; set; }
    
        public string Name { get; set; }
    
        public Profile Profile { get; set; }
    }
    
    public class Profile
    {
        public Guid ProfileId { get; set; }
    
        public User User { get; set; }
    
        public string SomeValue { get; set; }
    }
    

    【讨论】:

    • 你说的是对的。问题是我想在 Profile 类中拥有一个 UserId 属性(映射到数据库中的 FK 列)以及 User 属性。
    猜你喜欢
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多