将手动DbSet添加到Partial类DbContext EntityFramework

时间:2016-05-10 09:04:36

标签: c# entity-framework entity-framework-6

我得到一个旧项目,我需要添加一个新的功能。 Edmx刚刚生成,我不想编辑或生成它。 我的想法只是添加一个新的部分类与我的两个新的DbSet:

public partial class MyContextClass
{
    public virtual DbSet<Labels> Labels { get; set; }
    public virtual DbSet<LabelsWeight> LabelsWeights { get; set; }
}

我的edmx生成原始的MyContextClass:

public partial class MyContextClass : DbContext
{ .... }

这是我的Business对象:

public class Labels
{
    public int Id { get; set; }
    public string Type { get; set; }
    public string Label { get; set; }
    public Nullable<bool> Active { get; set; }
    public string Operation { get; set; }
    public string Value { get; set; }
}

在DB中,我有:

CREATE TABLE [dbo].[Labels](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Type] [nvarchar](50) NOT NULL,
[Label] [nvarchar](100) NOT NULL,
[Active] bit NULL,
[Operation] [nvarchar](5) NULL,
[Value] [nvarchar](50) NULL,
 CONSTRAINT [PK.Labels] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,            
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

但我得到错误:

The entity type Labels is not part of the model for the current context.

这是我错过的吗?

4 个答案:

答案 0 :(得分:0)

您的Business对象,它可以更新:

public class Labels
{
    [Key]
    public int Id { get; set; }
    public string Type { get; set; }
    public string Label { get; set; }
    public Nullable<bool> Active { get; set; }
    public string Operation { get; set; }
    public string Value { get; set; }
}

答案 1 :(得分:0)

您应该在模型浏览器窗口中添加新的实体类型标签example

答案 2 :(得分:0)

最后,我最后通过edmx中的数据库生成模型,就像在DbFirst中一样,使用了edmx中的xml:

&LT; EntitySet ....

&LT; EntityType ....

&LT; EntitySetMapping ....

&LT;协会....(对于FK)

所以结束是不可能只使用部分类来添加DbSet ...... :(

答案 3 :(得分:0)

我使用DataContext而不是DBContext,我总是创建我的数据类,如下所示。

 [Table(Name = "AppSettings")]
public class AppSetting
{
    [Column(Name = "Id", IsPrimaryKey = true)]
    public Guid Id { get; set; }
    [Column(Name = "SettingName")]
    public string SettingName;
    [Column(Name = "SettingValue", UpdateCheck = UpdateCheck.Never)]
    public string SettingValue;


    public AppSetting()
    {
        SettingName = String.Empty;
        SettingValue = String.Empty;
    }

}

所以改变你的课程看起来像下面

     [Table(Name = "Labels")]
public class Labels
{
    [Column(Name = "Id", IsPrimaryKey = true, IsDbGenerated=true)]
    public int Id { get; set; }
     [Column(Name = "Type")]
    public string Type { get; set; }
     [Column(Name = "Label")]
    public string Label { get; set; }
     [Column(Name = "Active", CanBeNull=true)]
    public Nullable<bool> Active { get; set; }
     [Column(Name = "Operation")]
    public string Operation { get; set; }
     [Column(Name = "Value")]
    public string Value { get; set; }
}

您可能会有更好的结果