如何解决无法通过MVC3实体模型的数据注释声明非常规PK
| 我正在尝试为实体模型声明主键,该主键最终将被ASP.NET MVC3消耗以创建Controller类,因此,我正在用[Key]
属性修饰值:
Foobar.cs
using System.ComponentModel.DataAnnotations;
public class Foobar
{
[Key]
public string Foo { get; set; }
public string Bar { get; set; }
}
FoobarDbContext.cs
using System.Data.Entity;
public class FoobarDBContext : DbContext
{
public DbSet<Foobar> Foobars { get; set; }
}
尝试创建上述Controller时会导致以下错误:
---------------------------
Microsoft Visual Studio
---------------------------
Unable to retrieve metadata for \'Dotnet.Samples.AspNetMvc.Models.FoobarDBContext\'.
One or more validation errors were detected during model generation:
- System.Data.Edm.EdmEntityType: : EntityType \'Foobar\' has no key defined.
Define the key for this EntityType.
- System.Data.Edm.EdmEntityType: : EntityType \'FoobarDBContext\' has no key defined.
Define the key for this EntityType.
- System.Data.Edm.EdmEntitySet: EntityType: EntitySet __Foobars__
is based on type ?Foo? that has no keys defined.
- System.Data.Edm.EdmEntitySet: EntityType: EntitySet __FoobarDBContexts__
is based on type __FoobarDBContext__ that has no keys defined.
---------------------------
OK
---------------------------
任何建议将不胜感激。在此先感谢
更新
根据实体框架中的数据注释和代码优先
KeyAttribute用于指定
属性/列是主要内容的一部分
实体的密钥并适用于
仅标量属性。
因此,我想我必须继续创建“非语义”标识符(例如ѭ4),才能利用代码生成功能。
解决方法
这不是必须的,我有一个User类,其主键定义如下:
[Key]
public string UserName { get; set; }
并且可以完美运行...关于类FooBar的其他信息是否可能相关?
另一方面,标量属性是“映射到存储架构中单个字段的实体的属性”,因此尝试将字符串属性用作PK不会成为问题。我知道这不是一个很有帮助的评论,但它表明存在其他情况。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。