我想在我从数据库映射的某个实体上创建一个自定义属性,但是这个属性没有映射到数据库,我使用部分类创建了属性但是在尝试编译时我得到一个错误告诉我属性未映射。是否有属性或我应该添加的内容?提前谢谢。
答案 0 :(得分:94)
您还可以使用[NotMapped]
属性标记您的媒体资源,或使用来自流利API的Ignore
方法。
<强>属性强>
public class EntityName
{
[NotMapped]
private string PropertyName { get; }
}
Fluent API
public class Entities : DbContext
{
public DbSet<EntityType> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Some database configuration
modelBuilder.Entity<EntityType>()
.Ignore(i => i.PropertyName);
}
}
答案 1 :(得分:10)
使用部分类添加要添加的属性或方法。 E.g。
namespace WhateverNamespaceYourEntityModelIsIn
{
public partial class TheNameOfYourEntity
{
public string MyNewProperty { get; set; }
}
}
那应该是你。
答案 2 :(得分:1)
我在谈话中已经很晚了,但您还想将partial标记为可序列化,将属性标记为可序列化 - 如果您计划使用JSON或序列化对象:
[Serializable()]
public partial class MyClass {
private System.Nullable<int> _Age;
[global::System.Runtime.Serialization.DataMemberAttribute(Order = 4)]
public System.Nullable<int> Age {
...
}
}
需要[Serializable()]和[global:]指令。如果您排除[global:],则无论何时将其序列化,都会被忽略,并且不会包含在序列化中。
答案 3 :(得分:1)
这个页面对我很有帮助。在看到Kniganapolke的回答之后,我会准确添加我添加到映射配置中的内容。
public TheObjectName()
{
this.HasKey(t => t.ID);
this.Ignore(t => t.IsProcess); //we don't want EF to worry about this
}
谢谢大家,谢谢!