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
Related
When trying to create a new database entry of type TestForm2 I include the related object Unit Type's ID as a foreign key, except when I perform context.SaveChanges() after adding the new model I get the following SQL exception:
SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.UnitTypes'. Cannot insert duplicate key in object 'dbo.UnitTypes'. The duplicate key value is (2d911331-6083-4bba-a3ad-e50341a7b128). The statement has been terminated.
What this means to me is that it thinks that the foreign entry I'm trying to relate to the new model is instead a new object that it's attempting to insert into the UnitTypes table and failing because it sees an existing entry with the same primary key.
For context (pun not intended), this is my data context, the database model, and the erroring "Create" function.
public class DataContext : IdentityDbContext<ApplicationUser>
{
public DataContext() : base("DefaultConnection")
{
}
public static DataContext Create()
{
return new DataContext();
}
public DbSet<SafetyIncident> SafetyIncidents { get; set; }
public DbSet<ProductionLine> ProductionLines { get; set; }
public DbSet<ProductionOrder> ProductionOrders { get; set; }
public DbSet<SerialOrder> SerialOrder { get; set; }
public DbSet<QualityError> QualityErrors { get; set; }
public DbSet<PSA> PSAs { get; set; }
public DbSet<TestStation> TestStations { get; set; }
public DbSet<ProductionGoal> ProductionGoals { get; set; }
public DbSet<DailyWorkStationCheck> DailyWorkStationChecks { get; set; }
public DbSet<TestForm> TestForms { get; set; }
public DbSet<User> AppUsers { get; set; }
public DbSet<Options> Options { get; set; }
public DbSet<DriveList> DriveSerials { get; set; }
public DbSet<MRPController> MRPControllers { get; set; }
public DbSet<TestOption> TestOptions { get; set; }
public DbSet<UnitType> UnitTypes { get; set; }
public DbSet<UnitTypeMap> UnitTypeMaps { get; set; }
public DbSet<TestForm2> TestForm2s { get; set; }
public DbSet<TestFormSection> TestFormSections { get; set; }
public DbSet<TestFormSectionStep> TestFormSectionSteps { get; set; }
}
public class TestForm2 : BaseEntity
{
public string SerialNumber { get; set; }
public string MaterialNumber { get; set; }
public string UnitTypeId { get; set; }
public UnitType UnitType { get; set; }
public bool UsesStandardOptions { get; set; }
public bool OptionsVerified { get; set; } // This will only be used when UsesStandardOptions is true, otherwise its value doesn't matter
public ICollection<TestOption> AllOptions { get; set; } // List of all options (at time of form creation)
public ICollection<TestOption> Options { get; set; } // The options on a unit
public ICollection<TestFormSection> Sections { get; set; }
}
public FormViewModel Create(FormViewModel vm)
{
using (var context = new DataContext())
{
List<string> optionListStrings = GetOptionListForModelNumber(vm.MaterialNumber); // returns list of option codes
List<TestOption> matchingOptions = context.TestOptions
.Where(optionInDb =>
optionListStrings.Any(trimOption => trimOption == optionInDb.OptionCode)).ToList();
var unitType = context.UnitTypes.FirstOrDefault(x => x.Name == vm.UnitType);
string unitTypeId = unitType.Id;
TestForm2 newForm = new TestForm2
{
// ID & CreatedAt instantiated by Base Entity constructor
SerialNumber = vm.SerialNumber,
MaterialNumber = vm.MaterialNumber,
UnitTypeId = unitType.Id,
UsesStandardOptions = vm.UsesStandardOptions,
OptionsVerified = vm.OptionsVerified,
//AllOptions = context.TestOptions.ToList(),
//Options = matchingOptions,
Sections = vm.Sections,
};
context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
context.TestForm2s.Add(newForm);
context.SaveChanges(); // THIS IS WHERE THE SQL EXCEPTION IS HAPPENING
return vm;
}
return null;
}
Lastly, I'm not sure if it's relevant, but a full copy of the related UnitType is viewable as part of newForm only after context.TestForm2s.add(newForm) resolves. This is weird to me since I don't think it should be automatically relating the data object like that.
I haven't been able to try much since everything looks properly configured to me. Please let me know if this is not the case or if I should include any other info.
Found the issue. The vm.Sections was not using viewmodels to contain the section data, so the vm.Sections contained UnitType database models. Since this was instantiated in the controller (before opening the data context in the TestForm2 Create method) EF assumed that these data were new and needed to be added to the UnitType table.
Hope this thread helps someone else running into similar issues.
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; }
}
Hello everyone so here is my basic EF class structure:
public abstract class StandardEngineeredModel
{
[Key]
public string ModelNumber { get; set; }
public int VoltageInput { get; set; }
}
public class DualRatedInputEngineeredModel : StandardEngineeredModel
{
public int SinglePhaseVoltageInput { get; set; }
public string SinglePhaseHzInput { get; set; }
public decimal SinglePhaseAmpsInput { get; set; }
public bool SeparateInput { get; set; }
}
And my context:
public class LabelPrintingContext : DbContext
{
public virtual DbSet<StandardEngineeredModel> StandardEngineeredModels { get; set; }
}
What I am trying to do is query for a StandardEngineeredModel. Here is an example of a query I tried:
public StandardEngineeredModel GetEngineeredOrder(string modelNumber)
{
using (context = new LabelPrintingContext())
{
return (from s in context.StandardEngineeredModels
where s.ModelNumber == modelNumber
select s).FirstOrDefault();
}
}
But when executing this it says invalid column name SeparateInput which seems to be happening because of the extra column being added to my StandardEngineeredModels table due to the DualRatedInputEngineeredModel inheriting from it. Not sure how to go about this, I don't want to return an Iqueryable, but no matter what I try it tells me the SeparateInput is an invalid column name.
I also tried casting it first and get the same error:
public StandardEngineeredModel GetEngineeredOrder(string modelNumber)
{
using (context = new LabelPrintingContext())
{
return (from s in context.StandardEngineeredModels.OfType<StandardEngineeredModel>()
where s.ModelNumber == modelNumber
select s).FirstOrDefault();
}
}
Do I need to make a DTO or something? Am I just doing this completely wrong?
Thanks in advance for any opinions / help!
I am using Entity Framework 6 in a project and am having trouble creating a query.
Say my classes are defined like:
public class MyContext : DbContext
{
public MyContext(string connectionString) : base(connectionString)
{
}
public DbSet<EntityXXX> XXXSet { get; set; }
public DbSet<EntityYYY> YYYSet { get; set; }
}
public class EntityXXX
{
public string XXXName { get; set; }
public int id { get; set; }
public int YYYid { get; set; }
}
public class EntityYYY
{
public string YYYName { get; set; }
public int id { get; set; }
}
The YYYid property of EntityXXX is the 'id' of the EntityYYY instance that it relates to.
I want to be able to fill a Grid with rows where the first Column is XXXName and the second column is YYYName (from its related EntityYYY), but I can't see how to do this?
I'm sure it's really simple, but I'm new to EF.
You need to put a virtual navigation property on your EntityXXX
public virtual EntityYYY YYY { get; set; }
Then you can do a projection:
db.XXXSet
.Select(x => new { x.XXXName, YYYName = x.YYY.YYYName })
.ToList();
Which will get you the list you need.
I am having troubles trying to figure out how to use the EF6 interceptors to set a value on Insert/Update.
What I wanted to do is to have an interceptor to automatically create a new instance of Audit like so:
public class FooContext : DbContext
{
public DbSet<Invoice> Invoices { get; set; }
public DbSet<Audit> Audits { get; set; }
}
public class Invoice
{
public int Id { get; set; }
public string Name { get; set; }
public Audit AuditAndConcurrencyKey { get; set; }
}
public class InvoiceItem
{
public int Id { get; set; }
public Invoice Header { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
//For legacy reasons. I know this design is wrong :(
public Audit AuditAndConcurrencyKey { get; set; }
}
public class Audit
{
public int Id { get; set; }
public int InstanceId { get; set; }
public string Message { get; set; }
}
[Test]
public void WillCreateAudit()
{
using (var db = new FooContext())
{
var inv = new Invoice {Name = "Foo Invoice"};
var invLine = new InvoiceItem {Header = inv, Price = 1, Name = "Apple"};
db.Invoices.Add(inv);
db.SaveChanges();
//Inceptors should figure out that we are working with "Invoice" and "InvoiceLine"
//And automatically create an "Audit" instance
Assert.That(inv.AuditAndConcurrencyKey != null);
Assert.That(invLine.AuditAndConcurrencyKey != null);
Assert.That(inv.AuditAndConcurrencyKey == invLine.AuditAndConcurrencyKey)
}
}
The first thing I checked is this example for SoftDeleteInterceptor. I don't think this is what I want because it looks like at the point where we are already generating the expression tree, we are no longer aware of the type of object you are working with.
I checked this example as well, but again, it looks like we are injecting strings instead of setting object references.
Ideally I want something like this:
public class AuditInterceptor
{
public void Intercept(object obj)
{
if (!(obj is Invoice) && !(obj is InvoiceItem))
return; //not type we are looking for, by-pass
//Set the audit here
}
}