EF6 Foreign Key Conflict - c#

This is the content of my DivorceCases.cs file inside Models:
public class DivorceCases
{
public string case_id { get; set; }
public virtual Transactions t { get; set; }
}
public class DivorceCasesContext : DbContext
{
public DivorceCasesContext() : base("mssqlDB") { }
public DbSet<DivorceCases> DivorceCase { get; set; }
}
This is the content of my CorporationCases.cs file inside Models:
public class CorporationCases
{
public string case_id { get; set; }
public virtual Transactions t { get; set; }
}
public class CorporationCasesContext : DbContext
{
public CorporationCasesContext() : base("mssqlDB") { }
public DbSet<CorporationCases> CorporationCase { get; set; }
}
Now my question is:
I am using code-first approach to let EF6 create table for me automatically.
when I try to create and use any instance of table and EF6 creates it as well for DivorceCases Model and Context pair. But after the DivorceCases table has been created, I try to create and use CorporationCases Model instance then EF6 fails to automatically create the table for me because
"Transaction" Table has already been created by DivorceCases context
So how do I solve this issue?

You don't need to create 2 dbContext here.just use one as shown below.
Important Note : You're not following basic naming conventions.I highly recommend to use those.
one place is here : public DbSet<DivorceCases> DivorceCase { get; set; }
need to be corrected as public DbSet<DivorceCase> DivorceCases { get; set; }
Using One DbContext :
public class DivorceCases
{
public string case_id { get; set; }
public virtual Transactions t { get; set; }
}
public class CorporationCases
{
public string case_id { get; set; }
public virtual Transactions t { get; set; }
}
public class YourCasesContext : DbContext
{
public YourCasesContext () : base("mssqlDB") { }
public DbSet<DivorceCases> DivorceCase { get; set; }
public DbSet<CorporationCases> CorporationCase { get; set; }
}

Related

using entities as json objects in EF core

I have below model structure
public class A621
{
public Guid? AirflowSource { get; set; }
public string AirflowSourceName { get; set; }
public string Category { get; set; }
}
public class A170
{
public Guid? AirflowSource { get; set; }
public string AirflowSourceName { get; set; }
}
I am using above models in entities like as below
public class MechanicalData
{
public List<A621> A621 { get; private set; }
public List<A170> A170 { get; private set; }
public List<Lab> Lab { get; private set; }
}
public class MechanicalTypeData
{
public MechanicalData MechanicalData { get; set; }
}
public class SpaceType : IAEIMaster, IRevisionData
{
[Column(TypeName = "jsonb")]
public MechanicalTypeData MechanicalTypeData { get; set; }
public string Note { get; set; }
public bool IsApproved { get; set; }
}
you can see that i am using this entity MechanicalTypeData in spacetype entity as json column and these entities A621 and A170 are child entities of MechanicalData ..
Now i would like to use A621 and A170 as a individual lookup tables and these are going to be really existing in DB. I am using EF core code first approach while creating tables.
my question is can i use A621 and A170 for both purposes, by both I mean as individual lookup tables and adding child objects to json that is going to be sit in column as json object.
Could any one throw some light on this or any other better approach as well.
many thanks in advance

Creating different tables using using same base abstract class

I have 2 models which have exactly same fields, but I chose to make different models for them because I needed two different tables, one for each.
Earlier everything was working fine when I had two different tables for each model, but then I started using abstract base class because the code inside both the models were same.
Now I have a single table comprised of all the data that I save.
How can I create different tables for those two models.
public abstract class baseGrammar
{
[Key]
public int Id { get; set; }
[Required]
public string question { get; set; }
[Required]
public string ans { get; set; }
public string ruleId { get; set; }
public string ruleApplicable { get; set; }
[ForeignKey("ruleId")]
public virtual ruleTable RuleTable { get; set; }
}
The one shown above is my abstract base class.
public class article : baseGrammar
{
}
public class adjective : baseGrammar
{
}
Just if someone intrested in ruleTable model.
public class ruleTable
{
[Key]
public string ruleId { get; set; }
public string topic { get; set; }
public string rule { get; set; }
public string example { get; set; }
public virtual ICollection<baseGrammar> BaseGrammar { get; set; }
}
Am also adding context class so as to provide better description
public class english : DbContext
{
public english() : base("name=localServerEng")
{
Database.SetInitializer<DbContext>(null);
Database.SetInitializer<english>(new UniDBInitializer<english>());
}
public virtual DbSet<adjective> adjectiveDb { get; set; }
public virtual DbSet<adverb> adverbDb { get; set; }
public virtual DbSet<alternativeVerb> alternativeVerbDb { get; set; }
public virtual DbSet<antonyms> antonymsDb { get; set; }
public virtual DbSet<article> articleDb { get; set; }
private class UniDBInitializer<T> : DropCreateDatabaseIfModelChanges<english>
{
}
public System.Data.Entity.DbSet<StructureSSC.Areas.AreaEnglish.Models.baseGrammar> baseGrammars { get; set; }
}
Screenshot of SQL Server showing 1 table comprising of all columns instead of different tables
This set up will give you 2 tables: (1) adjectives (2) articles
The context should be like this:
public class SomeContext : DbContext
{
public SomeContext()
: base("name=SomeContext")
{
}
public virtual DbSet<article> Articles { get; set; }
public virtual DbSet<adjective> Adjectives { get; set; }
}
public abstract class baseGrammar
{
//... common properties/columns
}
public class article : baseGrammar
{
}
public class adjective : baseGrammar
{
}
Please note the naming convention. In .NET class names and property names should follow Pascal Notation. Therefore, they should be:
BaseGrammar
Article
Adjective
RuleApplicable // other properties should follow same convention

.NET Core - Adding Scaffolded Item "There was an Error creating the DbContext to get the model"

Whenever I attempt to create a new scaffolded item for my project, I receive an error stating
There was an error creating the DbContect instance to get the model
No Parameterless constructor defined for this object.
I have attempted to rebuild my project, and I have had success generating scaffolds prior, however for some reason when doing so now I haven't had any success. No alterations have been done to my context class since I last added a new scaffolded item.
I have attempted to create an empty constructor in my model however it still tosses the same error. Below you will find my code for my model I'm trying to scaffold, and my context.
namespace HRIAT.Models
{
public class Credential
{
public Credential() { }
public int ID { get; set; }
public string credentialName { get; set; }
public FundingSource credentialFundingSource { get; set; }
public string credentialType { get; set; }
public float credentialCost { get; set; }
public ICollection<Employee> ec { get; set; }
}
}
Context class:
namespace HRIAT.Models
{
public class HRIATContext : DbContext
{
public HRIATContext(DbContextOptions<HRIATContext> options)
: base(options)
{
}
public DbSet<FundingSource> FundingSource { get; set; }
public DbSet<Credential> Credential { get; set; }
public DbSet<Employee> Employee { get; set; }
public DbSet<EmployeesCredentials> EmployeeCredential { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EmployeesCredentials>().HasKey(c => new { c.CredentialID, c.employeeNum });
}
public DbSet<Position> Positions { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Location> Locations { get; set; }
}
}
This error appears if the entities of your project do not contains an empty constructor. EntityFramework needs the empty constructor to instantiate the entity and maps properties of schema.
If you needs protect the entity classes, use the protected constructor, example:
public class Person
{
public string Name { get; private set; }
public Person(string name)
{
Name = name;
}
protected Person() { }
}

Empty Migrations are generated in code first ASP.NET MVC

I have been trying to generate migration but some reason, generated migrations is empty except the basic definition of function up and down but empty inside.
Model class
public class StoryDB
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid id { get; set; }
[Required]
public string StoryContent { get; set; }
private int heartsCount { get; set; }
private int commentsCount { get; set; }
private int shareCount { get; set; }
public DateTime dateCreated { get; set; }
public DateTime dateModified { get; set; }
}
Database Context class
public class StoreDB : DbContext
{
public StoreDB() : base("DefaultConnection")
{
}
public virtual DbSet <StoryDB> Stories { get; set; }
}
Note that I am using the same connection DefaultConnection which is used to by Identity Classes
When I generate the initial seeding class that generates perfectly (i.e. all user tables like roles and users)
However when i try to generate the first migration after seed class, then nothing appears in the class
You have to tell the DbContext which entities you want to map to the DB. In your case StoryDB:
public class StoreDB : DbContext
{
public StoreDB() : base("DefaultConnection")
{
}
public virtual DbSet<StoryDB> Stories { get; set; }
}
Note that DbSet has a generic parameter, which tells EF the actual type to use.

Cannot create Controller with actions using Entity Framework

I've created a Model using Model first and Entity Data Model of Entity Framework. Well, when I want to create the controller (right click on controllers folder Add->controller->WebApi 2 Controller with actions using EF) then I become after defining the inputfields an error message:
there was an error getting the type "WebApi.Models.QR_Name". Try rebuilding the project. The same error getting by the other Model class. How can I solve this??
EDIT:
I have two classes:
//Group
namespace WebApi.Models
{
public partial class QR_Group
{
public QR_Group()
{
this.QR_Name = new HashSet<QR_Name>();
}
public int Id { get; set; }
public string name { get; set; }
public string code { get; set; }
public virtual ICollection<QR_Name> QR_Name { get; set; }
}
}
//Name
namespace WebApi.Models
{
public partial class QR_Name
{
public int Id { get; set; }
public string firstname { get; set; }
public double maxAge { get; set; }
public int QR_GroupId { get; set; }
public virtual QR_Group QR_Group { get; set; }
}
}
Additionally is here the Context class:
namespace WebApi.Models
{
public partial class WebApiContext : DbContext
{
public WebApiContext()
: base("name=WebApiContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<QR_Group> QR_Groups { get; set; }
public virtual DbSet<QR_Name> QR_Names { get; set; }
}
}
Before creating your controller, press Ctrl+Shift+B to build your solution or go to 'Build->Build Solution' and then try creating your controller.

Categories

Resources