EF4 代码优先 CTP5 多对一
我一直在尝试让 EF4 CTP5 与现有数据库很好地配合,但在一些基本的映射问题上遇到了困难。
到目前为止我有两个模型类:
public class Job
{
[Key, Column(Order = 0)]
public int JobNumber { get; set; }
[Key, Column(Order = 1)]
public int VersionNumber { get; set; }
public virtual User OwnedBy { get; set; }
}
并且
[Table("Usernames")]
public class User
{
[Key]
public string Username { get; set; }
public string EmailAddress { get; set; }
public bool IsAdministrator { get; set; }
}
我有我的 DbContext 类将它们公开为 IDbSet
我可以查询我的用户,但是一旦我将 OwnedBy 字段添加到 Job 类中,我就开始在所有 Job 测试中收到此错误:
列名“UserUsername”无效。
我希望它的行为像 NHibernate 的多对一,而我认为 EF4 将其视为复杂类型。这应该怎么做呢?
I've been trying to get EF4 CTP5 to play nice with an existing database, but struggling with some basic mapping issues.
I have two model classes so far:
public class Job
{
[Key, Column(Order = 0)]
public int JobNumber { get; set; }
[Key, Column(Order = 1)]
public int VersionNumber { get; set; }
public virtual User OwnedBy { get; set; }
}
and
[Table("Usernames")]
public class User
{
[Key]
public string Username { get; set; }
public string EmailAddress { get; set; }
public bool IsAdministrator { get; set; }
}
And I have my DbContext class exposing those as IDbSet
I can query my users, but as soon as I added the OwnedBy field to the Job class I began getting this error in all my tests for the Jobs:
Invalid column name 'UserUsername'.
I want this to behave like NHibernate's many-to-one, whereas I think EF4 is treating it as a complex type. How should this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UserUsername
是 EF Code First 在作业表中为外键选择的默认名称。显然,它与现有数据库中 Jobs 表中的 FK 列的名称不同。您需要覆盖此约定并更改 FK 的默认名称,以便它与您的数据库匹配。以下是使用 Fluent API 的实现方式:UserUsername
is the default name that EF Code First chooses for the foreign key in the Jobs table. Obviously, it's not the same name that your existing database has for the FK column in Jobs table. You need to override this conventions and change the FK's default name so that it matches your database. Here is how it's done with fluent API:尝试让它从您的模式创建新数据库,并查看它期望的列名。
我认为它是 OwnedBy 的关键。它尝试根据其内部约定来命名它,这与您命名外键列的方式不兼容。不,它确实将其视为多对一。
Try let it create new database from your schema and look what columname it expect.
I think its foreing key for OwnedBy. It tries to name it according to its internal convention, that is incompatible with how you named your foreing key column. And no, its really treating it as many-to-one.