实体框架 CTP Code First 列命名和关系

发布于 2024-10-07 23:49:05 字数 532 浏览 1 评论 0原文

我刚刚开始查看新的实体框架 CTP5 代码的第一部分。

我有以下非常简单的实体。

User
 int Id;
 Account Account;

Account
 int Id;
 User AccountOwner;
 ICollection<User> Users;

因此,帐户有一个所有者(用户)并且可以有许多用户。这些关系被转换为数据库中的Accounts 表和Users 表。

在“用户”表中,我得到两个列,AccountIdAccountId1,是否有任何方法可以控制这些列的生成名称。另外,我实际上希望 Accounts 表上的 AccountOwner 属性有一个 UserId 列,但似乎引用位于相反,Users 表。如果所有键都没有 AccountId...n 那就太好了:)

I just started looking at the new Entity Framework CTP5 code first bits.

I have the following very simple entities.

User
 int Id;
 Account Account;

Account
 int Id;
 User AccountOwner;
 ICollection<User> Users;

So, accounts have an owner(User) and can have many users. These relationships is translated to an Accounts table and an Users table int the DB.

In the Users table I get two collumns, AccountId and AccountId1, is there any way to control the generated names for those columns. Also I would actually expect there to be a UserId column for the AccountOwner property on the Accounts table, but it seems that the reference is on the Users table instead. It would be really nice NOT to the have AccountId...n for all the keys :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绅士风度i 2024-10-14 23:49:05

这里发生了一些事情。

在用户和帐户彼此具有 1:1 关系的情况下,它会选择您不想要的一方。如果您不告诉它,它就无法知道将其放在哪一边,因此您可以使用 Fluent API 或属性来告诉它。您可能希望一侧可选,一侧必需,这将强制 FK 到另一侧,例如

User
...
[Optional]
Account Account;

Account
...
[Required]
User AccountOwner;

,或者您可以使用流畅的 API:

config.Entity<User>().HasOptional(u => u.Account).WithRequired(a => a.AccountOwner)

如果您遵循智能感知,您还可以使用约束属性来连接 FK 属性也。

要重命名 FK 属性(如果它们仍然不是您喜欢的属性),请使用 Column 属性,例如,

User
[Column(Name="Id")]
int Id;

或者再次使用 Fluent API:

config.Entity<User>().Property(u => u.Id).HasColumnName("Id");

There's a couple of things going on here.

In the case of User and Account having 1:1 relationships with each other it's choosing the side you don't want. There's no way for it to know which side to put it on without you telling it so you can tell it either with the fluent API or with an attribute. It's likely you want to make one side optional and one required which will force the FK to the other side, e.g.

User
...
[Optional]
Account Account;

Account
...
[Required]
User AccountOwner;

Alternatively you can use the fluent API:

config.Entity<User>().HasOptional(u => u.Account).WithRequired(a => a.AccountOwner)

If you follow intellisense on that you can also use the constraint property to wire up the FK properties too.

To rename the FK properties if they're still not what you like either use the Column attribute, e.g.

User
[Column(Name="Id")]
int Id;

Or again with the fluent API:

config.Entity<User>().Property(u => u.Id).HasColumnName("Id");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文