I'm getting the following exception when running the code bellow:
The entity type DomainUser is not part of the model for the current context.
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
namespace EFTest
{
class Program
{
static void Main(string[] args)
{
var dbContext = new DbContext(#"Data Source=...\sqlexpress;Initial Catalog=...;Integrated Security=True");
var entities = dbContext.Set<DomainUser>().ToList();
}
}
[Table("DomainUsers")]
public class DomainUser
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
}
UPDATE1
It works fine if I do specify the query, so what I'm a missing so that EF generates the query itself. I'm coming from an HNibernate+Fluent background.
class Program
{
static void Main(string[] args)
{
using (var dbContext = new DbContext(#"Data Source=...;Initial Catalog=...;Integrated Security=True"))
{
var entities = dbContext.Database.SqlQuery<DomainUser>("select * from DomainUsers;").ToList();
}
}
}
[Table("DomainUsers")]
public class DomainUser
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
UPDATE 2
I got it working with the code bellow, which I had already tested, the thing is, the SomeContext class does not provide any information that I can't provide when I'm using the generic DbContext directly and creating another dummy class just to have some dull properties is really a strange thing to me. They do a lot of type checking anyway, so why not have just one context and if the type used in the Set method is not contained in the context, just do some reflection and add it. I still find it strange that I really need to define a context all the time, let's see what other say
class Program
{
static void Main(string[] args)
{
using (var dbContext = new SomeContext(#"Data Source=...;Initial Catalog=...;Integrated Security=True"))
{
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var entities = dbContext.Set<DomainUser>().ToList();
}
}
}
[Table("DomainUsers")]
public class DomainUser
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
public class SomeContext : DbContext
{
public SomeContext(string conn) : base(conn) { }
public DbSet<DomainUser> DomainUsers { get; set; }
}
Any ideas of what is going on.
You need to add a property to the DbContext
public DbSet<DomainUser> DomainUsers { get; set; }
Once you have done that you should be able to do
dbContext.DomainUsers.ToList();
Update
I'd say it's always best practice to extend the context as follow
public class FunkyContext : DbContext
{
public DbSet<DomainUser> DomainUsers { get; set; }
}
Related
I'm training following aspnetboilerplate.com tutorials about developing using their frameworks. I'm stuck at the very first coding point where I have to create a basic table "Task" as stated in the code below.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(string title, string description = null)
: this()
{
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
I added the following code in my WebApp DBContext, too.
public class WebAppDbContext : AbpDbContext
{
public DbSet<Task> Tasks { get; set; } //<- This line
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
The tutorial does not mention any error regarding this code, but every time I make the command
Add-migration "Initial"
in the package manager console, I get this error.
The entity type "Task" requires a primary key to be defined.
I surfed the web for similar errors and each solution I've found does not work for me...
Update #1: I edited the code to this, but the error still remains.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Key]
public int Id { get; set; }
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(int id, string title, string description = null)
: this()
{
Id = id;
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
Tutorial link: https://aspnetboilerplate.com/Pages/Documents/Articles/Introduction-With-AspNet-Core-And-Entity-Framework-Core-Part-1/index.html
Update #2: This is the code of WebAppDbContext.cs
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
I've tried to reproduce your codes on my end and I noticed that the problem that you're dealing with is due to the wrong namespaces in the context WebAppDbContext.
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
//using System.Threading.Tasks;//<------------ this line causes the error
using WebApp.Tasks; //<----------- You need to add this namespace.
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
The problem is due to a conflict in the naming convention. I would recommend changing the name of the entity to something else to prevent further conflicts in the future.
I have graphql.net implementation using conventions
I have my model defined as below.
public partial class Project
{
public Project()
{
ProjectGroup = new HashSet<ProjectGroup>();
ProjectUser = new HashSet<ProjectUser>();
Datasource = new HashSet<Datasource>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProjectGroup> ProjectGroup { get; set; }
public virtual ICollection<ProjectUser> ProjectUser { get; set; }
public virtual ICollection<Datasource> Datasource { get; set; }
}
I am trying to update only name of above class.
using above class (which is basically kind of entity framework class, but that is irrelevant of this question)
So I have defined mutation as below.
public sealed class Mutation
{
public async Task<Project> SaveProject([Inject] IProjectRepository projectRepository, projectModels.Master.Project project)
{
return Mapper.Map<Project>(await projectRepository.SaveProject(project));
}
}
and I am calling this mutation as below.
axios
.post('https://localhost:44375/api/Graph', {
query: `mutation ($project: Project) {
saveProject(project: $project) {
name
}
}`,
variables: {
'project': { 'name' : data.label },
},
})
In response I am getting below error.
{"errors":[{"message":"Variable \"project\" cannot be non-input type \"Project\".","locations":[{"line":1,"column":11}],"extensions":{"code":"VALIDATION_ERROR"}}]}
what am I doing wrong?
From graphql.net convention's official repo, I found one example and there was one attribute used for input type. After use of that it is working.
https://github.com/graphql-dotnet/conventions/blob/master/samples/DataLoaderWithEFCore/DataLoaderWithEFCore/GraphApi/Schema/InputTypes/UpdateMovieTitleParams.cs
So it requires attribute something in a following way.
[InputType]
public class UpdateMovieTitleParams
{
public Guid Id { get; set; }
public string NewTitle { get; set; }
}
I currently have 2 dbcontext classes set up that use different connection strings. Whenever I try to select from the "Cedulados" table it winds up using the "DefaultConnection" string for some reason. What am I doing wrong?
public class DataContext : DbContext
{
public DataContext()
: base("DefaultConnection")
{
}
public DbSet<SEG_CEmpleados> Empleados { get; set; }
public DbSet<SEG_CEmpNuevo> EmpleadosNuevos { get; set; }
public DbSet<SEG_Estados> Estados { get; set; }
public DbSet<SEG_Tarjetas> Tarjetas { get; set; }
public DbSet<SEG_Visitantes> Visitantes { get; set; }
public DbSet<SEG_Tipos> Tipos { get; set; }
public DbSet<SEG_TiposDoc> TiposDoc { get; set; }
public DbSet<SEG_Departamentos> Departamentos { get; set; }
internal void Refresh(RefreshMode clientWins, object articles)
{
throw new NotImplementedException();
}
}
public class CeduladosContext : DbContext
{
public CeduladosContext()
: base("Cedulados")
{
}
public DbSet<Cedulados20110712> Cedulados { get; set; }
internal void Refresh(RefreshMode clientWins, object articles)
{
throw new NotImplementedException();
}
}
public JsonResult PerCedula(string id)
{
string mun = id.Substring(0, 3);
string seq = id.Substring(3, 7);
string ver = id.Substring(10, 1);
var context = new CeduladosContext();
var ced = context.Cedulados.FirstOrDefault();
return Json(ced, JsonRequestBehavior.AllowGet);
}
Try this (note "name=" in the constructor parameter):
public DataContext() : base("name=DefaultConnection")
public CeduladosContext() : base("name=Cedulados")
You can find more information here.
I searched MSDN for the DbContext Constructor and it says it takes the database name or connection string as a parameter. In your question, you said you are selecting from the table Cedulados, which you are also passing to your DbContext. It seems you should pass the database name instead of the table name. Or is your database also named "Cedulados?
https://msdn.microsoft.com/en-us/library/gg679467(v=vs.113).aspx
Here is another resource demonstrating similar code with explanations to what you posted.
https://msdn.microsoft.com/en-us/data/jj592674.aspx
How to use DbRef in LiteDB. I have classes for both Customer and Job. I want the Customer to store a list of jobs that the Customer has.
So in the Customer class, I need to have aDbRef<Job> Jobs from what I understand. I have several issues. First, DbRef is not recognized as a type with using LiteDB. Second, I have no idea how to implement it
Job.cs
namespace HMDCompare.Classes
{
public class Job
{
public int id { get; set; }
public string name { get; set; }
}
}
Customer.cs
using LiteDB;
namespace HMDCompare.Classes
{
public class Customer
{
[BsonId]
public int Id { get; set; }
public string Name { get; set; }
public string[] Phones { get; set; }
public bool IsActive { get; set; }
public DbRef<Job> Jobs { get; set; }
}
}
for the DbRef I get in Visual Studio: The type or Namespace name 'DbRef' could not be found.
I am developing in C#/ASP.net 4.5 and with LiteDB 2.0.0-rc
Using LiteDB.2.0.0-rc and following the example in test page, worked fine for me.
public IncludeDatabase() : base("mydb.db")
{
}
public LiteCollection<Folder> Folders { get { return this.GetCollection<Folder>("Folders"); } }
public LiteCollection<SubFolders> SubFolders { get { return this.GetCollection<Media>("SubFolders"); } }
protected override void OnModelCreating(BsonMapper mapper)
{
mapper.Entity<SubFolder>()
.DbRef(x => x.Folder, "Folders");
}
.....
add
var subFolder = new SubFolder()
{
Name = file.Name,
Folder = new Folder { Id = idFolder },
};
using (var db = new IncludeDatabase())
{
db.SubFolders.Insert(subFolder);
}
get
using (var db = new IncludeDatabase())
{
return db.SubFolders
.Include(x => x.Folder)
.FindAll().ToList();
}
This question is related to this question which was never answered. I have a more real world example here though - so hoping for some help.
I have an auction, bid and auctiondetail(a flattened table) class.
I am trying to include my bids in the auction as well as auctiondetail table, auction and auctiondetail have the same PK
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace OnCall.VirtualWarehouse.Data.Models.Auctions
{
using System;
public class AuctionCopy
{
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
public class BidCopy
{
public Guid BidCopyId { get; set; }
public Guid AuctionCopyId { get; set; }
public AuctionCopy AuctionCopy { get; set; }
}
public class AuctionDetailCopy
{
[Key]
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
}
Here's my DBContext:
public class DataContext : DbContext
{
static DataContext()
{
Database.SetInitializer(new DropCreateIfChangeInitializer());
}
public DataContext()
{
Configuration.ProxyCreationEnabled = false;
}
public IDbSet<AuctionCopy> AuctionCopy { get; set; }
public IDbSet<BidCopy> BidCopy { get; set; }
public IDbSet<AuctionDetailCopy> AuctionDetailCopy { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public void Seed(DataContext context)
{
}
}
When generating the database, I get
The operation failed because an index or statistics with name 'IX_AuctionId' already exists on table 'Bids'.
Any ideas how I can get this to work?
The bug come from EF4.3 (and 4.3.1).
It should be fixed for the next release.
Have a look on Unhandled Exception after Upgrading to Entity Framework 4.3.1. They purpose a workaround using migration system.