Ale*_*dro 5 entity-framework entity-framework-5 visual-studio-2012
我在VS2012上使用EF5,当表生成时我遇到了问题.
1)我创建了一个包含2个表的简单数据库模式(edmx):
属性:名称(字符串)
表2:角色
2)将唯一键的属性(称为Id)定义为:
3)实体模型的属性是:
4)生成相关的类,但不存在[Key]属性:
using System;
using System.Collections.Generic;
public partial class Person
{
public Person()
{
this.Role = new HashSet<Role>();
}
//[Key] <-- Missed!
public System.Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Role> Role { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
5)我创建一个域服务,将上述实体暴露给客户端,如:
[EnableClientAccess]
public class DomainService1 : DomainService
{
[Query]
public IEnumerable<Person> GetPersonSet()
{
}
[Update]
public void UpdatePerson(Person person)
{
}
[Insert]
public void InsertPerson(Person person)
{
}
[Delete]
public void DeletePerson(Person person)
{
}
}
Run Code Online (Sandbox Code Playgroud)
6)重建并得到错误:
DomainService"DomainService1"中的实体"Person"没有定义密钥.DomainService操作公开的实体类型必须至少有一个用KeyAttribute标记的公共属性.
任何建议表示赞赏!
麦酒
您可以尝试更改.tt生成模板的代码,并在生成时向类添加属性.在您的情况下,您可以更改属性生成方法,如下所示:
public string Property(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
//Custom check for key field
(_ef.IsKey(edmProperty) ? "[Key]" : "") +
"{0} {1} {2} {{ {3}get; {4}set; }}",
Accessibility.ForProperty(edmProperty),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
Run Code Online (Sandbox Code Playgroud)
并为每个生成的类添加名称空间声明:
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
//Namespace for KeyAttribute goes here
"{0}using System; using System.ComponentModel.DataAnnotations;{1}" +
"{2}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}
Run Code Online (Sandbox Code Playgroud)
完成后,您可以单击.tt上的右键并选择"运行自定义工具"