Add manual DbSet to Partial class DbContext EntityFramework

c# entity-framework entity-framework-6

Question

I get an old project where I need to add a new functionnality. Edmx was generated a while ago and I don't want to edit it or generate it back. My idea is simply to add a new partial class with my two new DbSet:

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

My edmx generate the original MyContextClass:

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

Here is my Business object:

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; }
}

In DB, I have:

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]

But I get error:

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

Is it something that I missed ?

1
0
5/10/2016 9:04:36 AM

Popular Answer

I use DataContext not DBContext and I always create my data classes like below.

 [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;
    }

}

So alter you class to look like below

     [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; }
}

You may have better results

0
5/10/2016 11:39:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow