Glu*_*uip 22 entity-framework private-members ef-code-first
我正在使用EF 4.1,并且因缺乏枚举支持而寻找一个很好的解决方法.int的支持属性似乎是合乎逻辑的.
[Required]
public VenueType Type
{
get { return (VenueType) TypeId; }
set { TypeId = (int) value; }
}
private int TypeId { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是,如何将此属性设为私有并仍然映射它.换一种说法:
如何首先使用EF 4.1代码映射私有属性?
cri*_*mbo 72
这是一个可以在EF 6+中使用的约定来映射选定的非公共属性(只需将[Column]属性添加到属性).
在您的情况下,您将TypeId更改为:
[Column]
private int TypeId { get; set; }
Run Code Online (Sandbox Code Playgroud)
在你的DbContext.OnModelCreating,你需要注册约定:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new NonPublicColumnAttributeConvention());
}
Run Code Online (Sandbox Code Playgroud)
最后,这是惯例:
/// <summary>
/// Convention to support binding private or protected properties to EF columns.
/// </summary>
public sealed class NonPublicColumnAttributeConvention : Convention
{
public NonPublicColumnAttributeConvention()
{
Types().Having(NonPublicProperties)
.Configure((config, properties) =>
{
foreach (PropertyInfo prop in properties)
{
config.Property(prop);
}
});
}
private IEnumerable<PropertyInfo> NonPublicProperties(Type type)
{
var matchingProperties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0)
.ToArray();
return matchingProperties.Length == 0 ? null : matchingProperties;
}
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*ena 14
您不能先在EF代码中映射私有属性.您可以尝试将其更改为protected并在继承的类中进行配置 EntityConfiguration.
编辑
现在它已更改,请参阅此/sf/answers/966753651/
另一个解决方法可能是将您的字段设置为内部:
[NotMapped]
public dynamic FacebookMetadata {
get
{
return JObject.Parse(this.FacebookMetadataDb);
}
set
{
this.FacebookMetadataDb = JsonConvert.SerializeObject(value);
}
}
///this one
internal string FacebookMetadataDb { get; set; }
Run Code Online (Sandbox Code Playgroud)
并将其添加到游览模型中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.ManyToManyCascadeDeleteConvention>();
///here
modelBuilder.Entity<FacebookPage>().Property(p => p.FacebookMetadataDb);
base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26406 次 |
| 最近记录: |