Can't get EF Code First to work on SQL Server Express 2012 - entity-framework-4.1

I have tried the solutions mentioned in all the existing questions, but none of them work for me. When I run my application (runs with no errors), and go and check the SQLExpress Database (through SQL Management Studio), I can see that no tables have generated from my Code First classes.
Here is my connection string:
<add name="BSContext" connectionString="Data Source=.\SQLEXPRESS; Integrated Security=SSPI; Initial Catalog=BSDomain; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
I am on Win 8 Pro 64x, and using VS 2012 along with SQL Express 2012. And here is my BSContext code:
public class BSContext : DbContext
{
public DbSet<Event> Events { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Author> Authors { get; set; }
}
And in my application_start() I have the following:
Database.SetInitializer<BSContext>(new EventInitializer());
And the code for the EventInitializer is as follows:
public class EventInitializer : DropCreateDatabaseAlways<BSContext>
{
protected override void Seed(BSContext context)
{
// Seed Code
}
}
Still doesn't work.

Try to add this to your Application_Start() method in Global.asax.
System.Data.Entity.DropCreateDatabaseAlways<BSContext>());
This will force the application to create the DB every time your run the app, so don't leave it in there obviously!

It turns out it was simply because I was using the following format for my ID fields:
private int AuthorID { get; set; }
When I should have been using:
private int AuthorId { get; set; }
All works now !

Related

MySQLNumberTypeMapping' does not support value conversions

I've added a few models that I used to connect to a SQL database with and are now porting to MySQL . I am getting this error when I run : dotnet ef update --context {context}
Blockquote
System.NotImplementedException: The 'MySQLNumberTypeMapping' does not support value conversions. Support for value conversions typically requires changes in the database provider.
at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping.Clone(ValueConverter converter)
at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.b__7_0(ValueTuple3 k)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo& mappingInfo, IReadOnlyList1 principals)
at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMapping(MemberInfo member)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyDiscoveryConvention.IsCandidatePrimitiveProperty(PropertyInfo propertyInfo)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyDiscoveryConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.RunVisitor.VisitOnEntityTypeAdded(OnEntityTypeAddedNode node)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.VisitConventionScope(ConventionScope node)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.VisitConventionScope(ConventionScope node)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RelationshipDiscoveryConvention.DiscoverRelationships(InternalEntityTypeBuilder entityTypeBuilder) ...
The 'MySQLNumberTypeMapping' does not support value conversions. Support for value conversions typically requires changes in the database provider.
Here's on of the tables im expected to get created: (I've removed any reference to DataType(*) or enums that I though might be the issue with MySQL.
[Key]
public int ID { get; set; }
[StringLength(50)]
public string Name { get; set; }
public int? PropertyID { get; set; }
public Property Property { get; set; }
//public SelectList Animals { get; set; }
//public string AnimalTypes { get; set; }
[Display(Name="Spesie")]
public int? AnimalTypeID { get; set; }
[Display(Name = "Spesie")]
public AnimalType AnimalType { get; set; }
public bool Male { get; set; }
public bool Trophy { get; set; }
public int Quantity { get; set; }
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "R{0:N}")]
public decimal Price { get; set; }
[StringLength(2000)]
public string Comments { get; set; }
Why is MySQL not liking these definitions? or what is this value conversions its trying to do?
In order to continue development I found a suitable solution was to
Install-Package Pomelo.EntityFrameworkCore.Mysql -version
2.1.0-rc1-final
using nuget console and modify any reference of options.UseMySQL to options.UseMySql.
This allowed me to continue with dotnet 2.1 and utilize a mysql database.
Hope this helps!
The MySQL data provider does not implement the value conversion feature. You are getting this exception because you are using enums as data types which must be converted by the MySQL data provider which does not implement this feature and therefore throws a NotImplementedException.
This bug has already been reported: https://bugs.mysql.com/bug.php?id=89855
There is also an open github issue: https://github.com/aspnet/EntityFrameworkCore/issues/11078
In short, MySQL.Data.EntityFrameworkCore, running on .Net Core 2.0,
does not function correctly while using
Microsoft.EntityFrameworkCore.Relational 2.1.0-preview1-final, despite
claims that 2.0 conformant providers should work on it.
I was able to fix this issue by upgrading MySQL.Data.EntityFrameworkCore from 6.10.8 to 8.015 (released 2/1/2019) and upgrading .NET Core from 2.0 to 2.2.
I believe the issue has been fixed in version 8.

Setting mysql connection string at run time in MVC database first

I have a MVC project(data base first) with one SQL connection string.for applying this connection I use this way and it's connected correctly:
http://www.c-sharpcorner.com/UploadFile/8a67c0/database-first-approach-with-Asp-Net-mvc-step-by-step-part-2/
But, My problem is about applying another connection at run time with MySQL database.In fact, I have several forms which need to SQL connection and several forms which need MySQL connection.On the other hands, MySQL connection must be set at run time.
So, I have two important questions:
1-How can I set MySQL connection string at run time (in associated my model)
2-How can I switch between two connections in different views in running project.
for more explanation you could see my model for creating MySQL connection as below:(these fields are set in view, after posting view connection must be connected)
public partial class BPMEngine
{
public int EngID { get; set; }
public string EngName { get; set; }
public string DBServer { get; set; }
public string DBName { get; set; }
public string DBUserName { get; set; }
public string DBPass { get; set; }
public string EngURL { get; set; }
public string AppRootPath { get; set; }
}
In application settings you specify connection string and in context class you pass the connections string.
I would suggest you to specifiy 2 (or as much as you need) connection strings and use multiple context classes, each for "communicating" with other DB.
Example:
in App.config:
<connectionStrings>
<add name="conn_str_number_1" .../>
<add name="conn_str_number_2" .../>
</connectionStrings>
Context classes:
class MyContext1 : DbContext
{
public MyContext() : base("name=conn_str_number_1")
{
//...
}
//...
}
Another one:
class MyContext2 : DbContext
{
public MyContext() : base("name=conn_str_number_2")
{
//...
}
//...
}
And in code use both context classes, so you can interact with both DBs.
To switch connection string at run-time you can use contextClass.Database.Connection.ConnectionString property. More info about it here.
There, also we can read: DbContext has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:
public class MyDbContext : DbContext
{
public MyDbContext( string nameOrConnectionString )
: base( nameOrConnectionString )
{
}
}
But you have to specify all connection strings before running program :)

Why two constructors when using Entity Framework's Code First Reverse Engineer capability?

I'm learning Entity Framework and have a question. Why when using EF Code First and Reverse Engineering an existing database do I get two constructors in my context class? I believe in the example below the first is ensuring my database is not recreated as I am connecting to an existing database, SixteenthSectionLegacy, and the second is identifying the connection string that is used in my app.config file... Why couldn't/shouldn't both be in the first constructor?
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using EFReverseEngineerTest.Models.Mapping;
namespace EFReverseEngineerTest.Models
{
public partial class SixteenthSectionLegacyContext : DbContext
{
static SixteenthSectionLegacyContext()
{
Database.SetInitializer<SixteenthSectionLegacyContext>(null);
}
public SixteenthSectionLegacyContext()
: base("Name=SixteenthSectionLegacyContext")
{
}
public DbSet<board> boards { get; set; }
public DbSet<BOARD1> BOARDS1 { get; set; }
public DbSet<Classification> Classifications { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new boardMap());
modelBuilder.Configurations.Add(new BOARD1Map());
modelBuilder.Configurations.Add(new ClassificationMap());
}
}
}
: base("Name=SixteenthSectionLegacyContext") tells EF which connectionstring it sould use by default. You can pass your own connection string name when you create an SixteenthSectionLegacyContext instance in Code.
using (var context = new SixteenthSectionLegacyContext("SixteenthSectionLegacyContext_2"))
{
}
Add the second connection string name in the app.config under <connectionStrings> </connectionStrings>
This is why there are 2 ones, if you don't pass anything the default connection string is used.

How to control the generated model's name in Microsoft ADO.NET Entity Framework 4.1?

When I try to use Microsoft ADO.NET Entity Framework 4.1 in our project, I can not control the generated model's name.
For example, see the code first,
public class Bank
{
[Key]
public Guid BankID { get; set; }
public string BankCardNumber { get; set; }
public string BankName { get; set; }
} public class MyContext : DbContext
{
public DbSet<Bank> Banks { get; set; }
} public class MyContextInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
}
}
The code above is ok and it will be generated a table name called "Banks" in our database, but we want to control the generated table name, like "bank" or "opbanks", so could tell me how to do this?
Thank you very much.
Try using the TableAttribute class. For reference, you can find a list of data annotations for EF 4.1 here.

Can you help me understand this C# code?

I'm reading Pro ASP.Net MVC2 and I've gotten to a point where nothing is explained well enough. For example, the following tells me to create this C# code manually:
Implementing the Auctions Domain Model
With LINQ to SQL, you can set up mappings between C# classes and an implied database schema either
by decorating the classes with special attributes or by writing an XML configuration file. The XML option
has the advantage that persistence artifacts are totally removed from your domain classes,4 but the
disadvantage that it’s not so obvious at first glance. For simplicity, I’ll compromise here and use
attributes.
Here are the Auctions domain model classes now fully marked up for LINQ to SQL:5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.Linq;
[Table(Name="Members")]
public class Member
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int MemberID { get; set; }
[Column]
public string LoginName { get; set; }
[Column]
public int ReputationPoints { get; set; }
}
[Table(Name = "Items")]
public class Item
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public int ItemID { get; internal set; }
[Column]
public string Title { get; set; }
[Column]
public string Description { get; set; }
[Column]
public DateTime AuctionEndDate { get; set; }
[Association(OtherKey = "ItemID")]
private EntitySet<Bid> _bids = new EntitySet<Bid>();
public IList<Bid> Bids { get { return _bids.ToList().AsReadOnly(); } }
}
Where exactly do I have to write this in? Or is he just displaying generated code by the Linq-to-sql DBML?
That's not generated code. That's how you use Linq mappings to map your classes to your database.
You just write it in a CS file. It can go anywhere, but if you're using ASP.NET MVC you'd usually put it in the Models folder.
See this: http://msdn.microsoft.com/en-us/library/bb386971.aspx