Unable to generate database tables from Migration MySQL Ef-Core - mysql

I am trying to generate database and tables using EF Core Migrations. I have a Class Library Project which has all the necessary entities and migration datas . I am referencing Class Library Project in another ASP.NET Core 2.1 Web Application .
When running
add-migration initial
command in Nuget Package Manager Console choosing Class Library Project, Migration file is generated in Class Library Project which is fine.
When I run command
update-database
choosing both class libary and web project, I get the message stating that :
No migrations were applied. The database is already up to date.
My DbContextClass:
public class UserDbContext:DbContext
{
public UserDbContext(DbContextOptions<UserDbContext> options) : base(options){}
public DbSet<LoginSession> login_sessions { get; set; }
public DbSet<Authentication> authentications { get; set; }
public DbSet<RolePermissionMap> role_permission_maps { get; set; }
public DbSet<Entity.User> users { get; set; }
public DbSet<Role> roles { get; set; }
public DbSet<UserRole> user_roles { get; set; }
}
I tried running
dotnet ef database update
command from console choosing Class Library project, I got an error message saying:
The specified framework version '2.1' could not be parsed The
specified framework 'Microsoft.NETCore.App', version '2.1' was not
found.
When I copied all important files from Class Library to another web application project i.e, migration file and web project in same file, everything works fine.
I am wondering why I got that error and unable to find solution when class library and web application are in separate files. Can anyone help me? I have many class libraries referenced in web application. So, I cannot port all the necessary files to another web application just to generate database tables.

I've run into similar issues before.
Two suggestions:
Please consider nuking your entire "Migration" (all directories, files, etc) from your project, then re-running dotnet ef migrations add..., followed by dotnet ef database update...
Consider using the Pomelo data provider for MySQL:
https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql

Related

BC30002 Error Unable to reference .net standard 2.0 components from .net framework 4.8

I have a .net standard 2.0 C# project which simply has the following content in one of the C# files:
namespace person.contact
{
public class contactDetail
{
public long contactNumber { get; set; }
public decimal contactAmount { get; set; }
}
}
I also have a .net framework 4.8 project in VB.NET that now references this project using a project reference that points to the .CSPROJ location
Within the .net framework 4.8 project, one of my files calls up the above public class like so:
Dim clientContact As New person.contact.contactDetail
clientContact.ContactNumber = 12345
clientContact.contactAmouunt = 1.00
Now my VS 2019 can go to the definition when I F12 on contactDetail in the vb file and runs without a problem. When I do a clean build though I face the error:
error BC30002: Type 'person.contact.contactDetail' is not defined.
Both projects are also signed however I do know that as .net standard is higher there could be an issue with the DLL? I have however had this working before.
May be, because of multiple reference of different version exist in you project. remove all references and add again the single reference.

Is there a way to connect ASP.NET Core Razor Pages Web App to MySQL Database

I'm new to both Web apps and MySQL, but I'm creating a web app using Razor Pages and I can't figure out how to connect a MySQL database.
All I've found online is either about connecting a Razor pages to SQL or connecting MySQL to a MVC Web app. There was someone asking an almost identical question here 2 years ago, but the only answer given seems to be for connecting MVC to MySQL.
Is there a way to connect a MySQL database to a razor pages web app? Thanks for any help!
Notes: I'm using Visual Studio 2019 and ASP.NET Core 3.1
Yeah, there is no controller class in Razor Pages, we do the logic in the PageModel class. Apart from this, they are almost the same as MVC. You just need to inject the DbContext into the PageModel. Depend on the link you refer, you can change the last part like below:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly IronManContext _context;
public IndexModel(ILogger<IndexModel> logger, IronManContext context)
{
_logger = logger;
_context = context;
}
public void OnGet()
{
var teams = _context.Teams;
}
}

MySQL Data Provider Not Showing in Entity Data Model Wizard

I am creating an MVC application with MySQL as backend. I am planning to use Entity Framework to work with this database. I already have a database so need to generate models from a database
Environment:
MySQL Server 5.7.21
MySQL for Visual Studio 1.27
Connector/NET 6.10.5
Visual Studio 2015
To Reproduce Issue:
Step 1: Add new item 'Ado.net Entity Data Model'
Step 2: Selected 'EF Designer from database' and click 'Next'
Step 3: Clicked 'New Connection'
There is no mysql connector available.
Other Details:
I already added "System. Runtime" deal as it shows error when installing Mysql. data. Ef6 from nugget
I changed "CopyLocal= true" in 'System. Data' assembly reference
I tried the same steps in Visual Studio 2017. Here I can see the provider in the step 3 but after click ok dialogue closed instead of showing table list
In Visual Studio 2015 and 17 initial time it shows the provider. when I tried next time it's not displaying
Please help. I am checking this for 2 days
To start working with VS 2013 and EF 6
Install the MySQL for Visual Studio 1.1.1
Install the Connector/Net 6.8.1 product.
To work with Database first please do the following
Add the reference for the new assembly called MySql.Data.Entity.EF6 and copy it to the bin forlder of your application.
Add the provider to your app/web config file on the providers for Entity Framework section with the following line:
Before you run the Wizard compile your application so the new changes are applied.
To work with Model First please do the following
Add the reference for the new assembly called MySql.Data.Entity.EF6 and copy it to the bin forlder of your application.
Add the ADO.Net Entity Model new or existing.
Select the T4 template corresponding to MySQL (SSDLToMySQL)
Right click on the model and then select Generate Script to Create Database. (A MySQL script should be generated for you to create your database).
Hope this helps a bit.
MySQL for Visual Studio 1.1.1
MySQL Connector/Net 6.8.1 Beta
As MaDOS mentioned, mySql is not realy supported. If you want to use EF anyway you have to do a code-first-attempt.
You have to write the mapping-classes, and tell EF that it should NOT change the db.
Example context with disabled db-changes
public class MySqlDbContext : DbContext
{
public DbSet<MyOrderClass> Orders { get; set; }
public MySqlDbContext(IDbConnection connection)
: base((DbConnection)connection, false)
{
Database.SetInitializer<MySqlDbContext>(null); // Disable db-changes by dbContext
}
}
You main Problem are the data-types. Outside the MS-world not all data-types are supported (Oracle also got some problems with DateTime). In example-class below the "Created"-column is handled as string, which always works. In your .Net-application, you have to implement "converter"-properties which map to the desired type.
Example-Class with mapping-configuration
[Table("TORDERS")]
public class MyOrderClass
{
[Column("ORDERID")]
public long Id { get; set; }
[Column("CREATED")]
public string CreatedString { get; set; }
[NotMapped]
public DateTime? Created
{
get
{
DateTime tmp;
if (DateTime.TryParse(this.CreatedString, out tmp))
return tmp;
return null;
}
set
{
this.CreatedString = value.HasValue ? value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null;
}
}
}
static void Main(params string[] args)
{
MyOrderClass tmp = new MyOrderClass() { CreatedString = "2018-01-01 11:11:11"};
Console.WriteLine(tmp.Created.ToString()); // This is how you want to work
tmp.Created = null;
Console.WriteLine(tmp.CreatedString); // this is surely not what you want to do
tmp.Created = new DateTime(2018,02,02,10,10,10);
Console.WriteLine(tmp.CreatedString); // Check if setter works ;)
}
Im not uptodate which types work, but with this you'll always be able to use EF.
We used it some time ago to access an existing db, which hat an awful db-schema anyway, because of the schema we hat to setup the datatypes anyway ;).
Could it be a 32bit vs 64bit problem?
Example: 64bit driver installed Visual studio is 32bit?
I have that problem all the time with oledb to Informix. your sofware will work perfectly in 64bit, but the tooling is 32bit.

Java EE and JPA under Glassfish, NoClassDefFound com/mysql/jdbc/ResultSetMetaData

I have a problem when I acces my MySql Database from an EJB. After deploying my EAR to the Glassfish server, and calling the method that use the entity class I get an exception like this:
java.lang.NoClassDefFoundError: com/mysql/jdbc/ResultSetMetaData
I am using a local MySql Database, the connection to these still works. To acces the tables of these Databese I am using entity classes generated by Netbeans. This classes are situated in external Library (OthelloLibrarie). Here you can also find the remote interface of my Session Bean.
I had to put the entity classes in an external library because I'm using them in an Enterprise Client Application which is connected to my EAR.
My Enterprise Application Project contains the main Session bean and somes Session beans from entity classes which uses my entity classes in the external Library. It also contains the persistence XML and it includes my JDBC driver:
The error appears when I call the method createPartie from the Client Application:
Partie p = eJBOthelloGame.createPartie(jTextFieldPseudo.getText());
SessionBeanOthelloRemote.java:
#Stateless
public class SessionBeanOthello implements SessionBeanOthelloRemote {
#EJB
private PlayerFacadeLocal playerFacade;
#EJB
private PartieFacadeLocal partieFacade;
#Override
public Partie createPartie(String player) {
//Ajout du tuple
Partie p = new Partie();
Player p1 = new Player();
p1.setId(1);
p1.setNom(player);
playerFacade.create(p1);
p.setPlayer1(p1);
partieFacade.create(p);
return p;
}
Partie and Player are Entity classes used with generated facades.
I searched yet on the web but I never found this kind of error. It seems that only the package or class ResultSetMetaData from JDBC has a problem and not the entire driver.
Can you help me?
You need to include in your project the mysql-connector-java.jar file that provides the MySql JDBC driver classes. As you are using Netbeans, just add it as a library jar.
You can find it, along with download and installation instructions, at this link.

How to work with Portable Class Library and EF Code-first?

I'm doing an Windows Phone app where I have a WebApi running in Azure.
I'm using the new "Portable Class Library" (http://msdn.microsoft.com/en-us/library/gg597391.aspx) for my "Models" project which is of cause shared between my WebApi project (this is a normale ASp.NET MVC 4 project) and my Windows Phone project.
This works great and the model (POCO) classes are serialized and deserialized just as I want.
Now I want to start storing some of my Models/POCO objects and would like to use EF Code-first for that, but that's kind of a problem as I can't add the EntityFramework assembly to my "Portable Class Library" project, and really I would not like to either as I only need a small part (the attributes) in my Models project.
So, any suggestions to how a approach this the best way?
UPDATE:
Well, it seems like I can actually add the EntityFramework assembly to the project, but that doesn't really help me, as the attributes I need to use lives in System.ComponentModel.DataAnnotations which can't be used on Windows Phone.
Any suggestions still?
Don't use attributes. Use fluent API instead and create separate assembly for persistence (EF) which will reference your model assembly. Persistence assembly will be use used by your WebAPI layer.
I use a modified approach than Mikkel Hempel's, without the need to use pre processing directives.
Create a standard .NET class library, call it Models
Create a partial class representing what you want to be shared
public partial class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
For non-portable code (like DataAnnotations), create another partial class and use Metadata
[MetadataTypeAttribute(typeof(Person.Metadata))]
public partial class Person
{
internal sealed class Metadata
{
private Metadata() { } // Metadata classes shouldn't be instantiated
// Add metadata attributes to perform validation
[Required]
[StringLength(60)]
public string Name;
}
}
Create a Portable Class Library, and add the class from step 2 "As Link"
When I need my domain-project across multiple platforms, I usually:
Create the standard .NET-class library project for the domain code
For each platform I create a platform specific class library
For each platform specific class library I add the files from the standard .NET-class library as links (Add existing files -> As link) and hence they're updated automatically when you edit either the linked file or the original file.
When I add a new file to the .NET-class library, I add it as links to the platform specific class libraries.
Platform specific attributes (i.e. Table and ForeignKey which is a part of the DataAnnotations-assembly) can be opted out using the pre-processor tags. Lets say I have a .NET-class library with a class and a Silverlight-project with the linked file, then I can include the .NET-specific attributes by doing:
#if !SILVERLIGHT
[Table("MyEntityFrameworkTable")]
#endif
public class MyCrossPlatformClass
{
// Blah blah blah
}
and only include the DataAnnotations-assembly in the .NET-class library.
I know it's more work than using the Portable Class Library, but you can't opt out attributes in a PCL like in the example above, since you're only allowed to reference shared assemblies (which again DataAnnotations is not).