C# - Entity Framework enable FK with SQLite - c#

I'm working in a Entity Framework + SQLite app, and i don't know how activate PRAGMA foreign_keys = 1 in the Model for C# application.
Here my model (My_model.Context.cs)
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class My_Model : DbContext
{
public My_Model()
: base("name=My_Model")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<My_TABLE1> My_TABLE1 { get; set; }
public virtual DbSet<My_TABLE2> My_TABLE2 { get; set; }
public virtual DbSet<My_TABLE3> My_TABLE3 { get; set; }
public virtual DbSet<My_TABLE4> My_TABLE4 { get; set; }
}
Any idea?
I have tried modify App.conf doesn't works.
I have found many examples but no works for me.

In your App.Config file, add "foreign keys=true" to the connection string, like this:
data source=c:\wherever\whatever.sqlite;DateTimeFormat=InvariantCulture;foreign keys=true

Related

EF keep existing data during automatic migration

I am having a strange issue where my EF Automatic Migrations are removing all of the data within from all tables whenever I make a change to any one of the Entity's.
I've seen this similar question however for the life of me I can't derive from the links what I am missing in my own implementation.
Note that the application works as completely fine, with data being retrieved and saved to the mysql database via EF - it's just a great annoyance to have to re-create all the data everytime I want modify an Entity.
I am using EF6.0 and a MySql database.
Context.cs
namespace Dock.Models
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DockContext : DbContext
{
public DockContext(): base("name=DockContext")
{
Database.SetInitializer(new DockInitializer());
}
public virtual DbSet<Profile> Profiles { get; set; }
public virtual DbSet<Dock> Docks { get; set; }
public virtual DbSet<Crate> Crates { get; set; }
public virtual DbSet<Subscription> Subscriptions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
Confirguration.cs
internal sealed class Configuration : DbMigrationsConfiguration<DockContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
CodeGenerator = new MySqlMigrationCodeGenerator();
}
protected override void Seed(DockContext context)
{
Profile admin = new Profile {
NotAPrimaryId = 168879070,
DisplayName = "Admin101"
};
context.Profiles.AddOrUpdate(a => a.NotAPrimaryId , admin);
context.SaveChanges();
}
}
And an example of one of the Entity's Dock.cs
namespace Dock.Entities
{
public class Dock
{
[Key]
public int DockId { get; set; }
public int ProfileId { get; set; }
public int GameId { get; set; }
public string GameData { get; set; }
public bool Active { get; set; }
// Navigational Properties
[ForeignKey("CrateId")]
public virtual List<Crate> Crates { get; set; } = new List<Crate>();
}
}
EF will create migration classes for you. You don't have to write them by hand.
Automatic migrations can cause problems in my experience when different team members commit updates at different times.
I've also had to hand-edit the generated code-based migrations on several occasions, something that can't be done with automatic migrations.
I suggest switching to manual migrations so that you have complete visibility into and control of the migration process.

Scaffold Models based on Entity Framework - Validation Errors

I have my application configured to use a SQLRoleManager. I simply created the database, configured the web.config, and let the application create and populate the database tables.
I would like an admin view to preform some simple operations such as add and remove users. Thus, I have created an entity framework data context using the scaffolding wizard and directed it to build around the tables only. (did not check views and stored procedures).
The next thing i wished to do was to then scaffold the controller and view and eventual the model for this data. When I right click controllers I select the add controller with views using entity framework. I fill out the appropriate information selecting an empty class for the model.
I receive the following error which indicates the data is missing keys yet they are in fact defined on the database and in the entity model. Any thoughts as to where i am going wrong here? Do I need to pre build the model? I was hoping to have visual studio create these automatically.
EDIT
Again, the tables all have primary and foreign keys. I can confirm this from Sql Management Studio as well as the .edmx diagram. The bellow code was auto generated. Do i need to add keys?
Context.edmx
UserRole_Context.tt > aspnet_Users.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IDM.DAL
{
using System;
using System.Collections.Generic;
public partial class aspnet_Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public aspnet_Users()
{
this.aspnet_PersonalizationPerUser = new HashSet<aspnet_PersonalizationPerUser>();
this.aspnet_Roles = new HashSet<aspnet_Roles>();
}
public System.Guid ApplicationId { get; set; }
public System.Guid UserId { get; set; }
public string UserName { get; set; }
public string LoweredUserName { get; set; }
public string MobileAlias { get; set; }
public bool IsAnonymous { get; set; }
public System.DateTime LastActivityDate { get; set; }
public virtual aspnet_Applications aspnet_Applications { get; set; }
public virtual aspnet_Membership aspnet_Membership { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<aspnet_PersonalizationPerUser> aspnet_PersonalizationPerUser { get; set; }
public virtual aspnet_Profile aspnet_Profile { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<aspnet_Roles> aspnet_Roles { get; set; }
}
}
UserRole_Context.Context.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IDM.DAL
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class IDMEntities : DbContext
{
public IDMEntities()
: base("name=IDMEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<aspnet_Applications> aspnet_Applications { get; set; }
public virtual DbSet<aspnet_Membership> aspnet_Membership { get; set; }
public virtual DbSet<aspnet_Paths> aspnet_Paths { get; set; }
public virtual DbSet<aspnet_PersonalizationAllUsers> aspnet_PersonalizationAllUsers { get; set; }
public virtual DbSet<aspnet_PersonalizationPerUser> aspnet_PersonalizationPerUser { get; set; }
public virtual DbSet<aspnet_Profile> aspnet_Profile { get; set; }
public virtual DbSet<aspnet_Roles> aspnet_Roles { get; set; }
public virtual DbSet<aspnet_SchemaVersions> aspnet_SchemaVersions { get; set; }
public virtual DbSet<aspnet_Users> aspnet_Users { get; set; }
public virtual DbSet<aspnet_WebEvent_Events> aspnet_WebEvent_Events { get; set; }
}
}
Connection String
<add name="IDMEntities" connectionString="metadata=res://*/DAL.UserRole_Context.csdl|res://*/DAL.UserRole_Context.ssdl|res://*/DAL.UserRole_Context.msl;provider=System.Data.SqlClient;provider connection string="data source=*******;initial catalog=IDM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>

dbcontext.entity.select not available in Visual Studio 2013

it's been a while since I work with EntityDataModel. I used to do things like:
var listaProductos = dbContext.Productos.Select(p => new
I just started a new web project with asp.net and added the entity data model but If i try to do the same as the example above I can't use ".Select". Do I need to install any Nuget package or something?
I work with Visual Studio 2013.
Thanks for your help.
You should add namespase to your file:
using System.Linq;
check your namespace and dbContext class.
Like
using ContosoUniversity.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ContosoUniversity.DAL
{
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}

Creating Primary Key field on MVC class

I am new to MVC and C#. I just stumbled on it and found it interesting. I encountered an issue which will not allow me proceed.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyHotel.Models
{
public class AccountTypes
{
public int AccountTypeID { get; set; }
public string AccountTypeName { get; set; }
}
}
I created the controler and the view thereafter.
And for this, I keep got this error:
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'AccountTypes' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet "AccountTypes" is based on type "AccountTypes" that has no keys defined.
I google that the answers were to add [Key] over the public int AccountTypeID { get; set; } so it could look like this:
namespace MyHotel.Models
{
public class AccountTypes
{
[Key]
public int AccountTypeID { get; set; }
public string AccountTypeName { get; set; }
}
}
But no result until now.
Note: I am using MVC 4
Description
Entity Framework CodeFirst recognize the key, by default, by name.
Valid names are Id or <YourClassName>Id.
Your property should named Id or AccountTypesId
Another way is to use the ModelBuilder to specify the key.
Sample
public class MyDbContext : DbContext
{
public DbSet<AccountTypes> AccountTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AccountTypes>.HasKey(x => x.AccountTypeID);
base.OnModelCreating(modelBuilder);
}
}
Mode Information
Entity Framework Code First Tutorial
Try using [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] property to indicate the key field.
The regular field would go with EntityKeyPropert=false.
public class MyDbContext : DbContext
{
public DbSet<AccountTypes> AccountTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AccountTypes>().HasKey(x => x.AccountTypeID);
base.OnModelCreating(modelBuilder);
}
}
Hi Peter it seens you are missing an "s"
Your Account int should be:
public int AccountsTypeID { get; set; }
Hope it can be solved; Fernando.

Entity Framework Code First MySql Pluralizing Tables

I am using the Microsoft Entity Framework with code first to manage my data (with MySQL). I have defined a POCO object, however, when I try to add data it says table Users doesn't exist. I looked in the DB and it created table User not Users. How can I remedy this? It is driving me nuts!
Thanks!
public class User
{
[Key,Required]
public int UserId { get; set; }
[StringLength(20), Required]
public string UserName { get; set; }
[StringLength(30), Required]
public string Password { get; set; }
[StringLength(100), Required]
public string EmailAddress { get; set; }
[Required]
public DateTime CreateDate { get; set; }
[Required]
public bool IsActive { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace YourNamespace
{
public class DataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<User> User { get; set; }
}
}
I have not used MySQL with EF yet but regardless I think the solution is unbias. You need to turn off Pluralize Table Convention.
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;
public class MyDbContext: DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Now EF will look for the literal of your object name to the table name.
Some great video tutorials are at http://msdn.microsoft.com/en-us/data/aa937723 under the Continue Learning Entity Framework. For additional learning experience, you can not specify the above but rather explicitly map the object 'user' to the table 'user'.
Additional References:
http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-fluent-api-samples.aspx
You can put an attribute on the class telling the name of the table:
[Table("Users")]
public class User
{
//...
}
...or you could use the fluent API. To do this you will override the OnModelCreating method in your DbContext class.
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Map(t => t.ToTable("Users"));
}
}
In future versions of EF, we've been promised the ability to write our own conventions. Thats not in there yet as of version 4.1...
(Haven't tried it with MySQL...)

Categories