شروع به کار با EF Core 1.0 - قسمت 3 - انتقال مهاجرتها به یک اسمبلی دیگر
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۵/۲۷ ۱۲:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
{
"version": "1.0.0-*",
"dependencies": {
"Core1RtmEmptyTest.Entities": "1.0.0-*",
"Microsoft.EntityFrameworkCore": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0",
"NETStandard.Library": "1.6.0"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
} {
"dependencies": {
// same as before
"Core1RtmEmptyTest.Entities": "1.0.0-*",
"Core1RtmEmptyTest.DataLayer": "1.0.0-*"
}
} D:\Prog\1395\Core1RtmEmptyTest\src\Core1RtmEmptyTest>dotnet ef migrations add InitialDatabase Your target project 'Core1RtmEmptyTest' doesn't match your migrations assembly 'Core1RtmEmptyTest.DataLayer'. Either change your target project or change your migrations assembly.
D:\Prog\1395\Core1RtmEmptyTest\src\Core1RtmEmptyTest.DataLayer>dotnet ef migrations add InitialDatabase No executable found matching command "dotnet-ef"
{
// same as before
"tools": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"imports": [
"portable-net45+win8"
]
}
},
// same as before
} D:\Prog\1395\Core1RtmEmptyTest\src\Core1RtmEmptyTest.DataLayer>dotnet ef migrations add InitialDatabase Could not invoke this command on the startup project 'Core1RtmEmptyTest.DataLayer'. This preview of Entity Framework tools does not support commands on class library projects in ASP.NET Core and .NET Core applications.
D:\Prog\1395\Core1RtmEmptyTest\src\Core1RtmEmptyTest.DataLayer>dotnet ef --startup-project ../Core1RtmEmptyTest/ migrations add InitialDatabase Done. To undo this action, use 'dotnet ef migrations remove'
D:\Prog\1395\Core1RtmEmptyTest\src\Core1RtmEmptyTest.DataLayer>dotnet ef --startup-project ../Core1RtmEmptyTest/ database update Applying migration '13950527070105_InitialDatabase'. Done.
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c_%%a_%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME: =0%") do (set mytime=%%a%%b)
dotnet ef --configuration Release --startup-project ../ProjName/ migrations add V%mydate%_%mytime% PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer PM> Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet –Pre PM> Install-Package Microsoft.EntityFrameworkCore.Design PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
{
"version": "1.0.0-*",
"dependencies": {
"Core1RtmEmptyTest.Entities": "1.0.0-*",
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.Design": "1.1.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",
"Microsoft.Extensions.Configuration.Abstractions": "1.1.0",
"NETStandard.Library": "1.6.1"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet": {
"version": "1.1.0-preview4-final",
"imports": [
"portable-net45+win8"
]
}
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
} {
"version": "1.0.0-*",
"dependencies": {
//.. other assemblies
"CacheManager.Serialization.Json": "0.9.1",
"EFSecondLevelCache.Core": "1.0.1",
"Microsoft.AspNetCore.Diagnostics": "1.1.0",
"Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.1.0",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.InMemory": "1.1.0",
"Microsoft.Extensions.Configuration.Binder": "1.1.0",
"Microsoft.Extensions.Options": "1.1.0",
"System.Linq": "4.3.0",
"System.Reflection": "4.3.0",
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.Design": "1.1.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",
"Microsoft.Extensions.Configuration.Abstractions": "1.1.0",
"NETStandard.Library": "1.6.1"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet": {
"version": "1.2.0-preview4-22736",
"imports": [
"portable-net45+win8"
]
}
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": [
"dnxcore50",
"portable-net45+win8"
]
}
}
}
مشکل در
خط فرمان PMC (package Manager console) رفع نشده است اما با اجرای
CMD.exe در مسیر پروژه DataLayer و با استفاده از دستور زیر عملیات
Migrations به درستی عمل میکند : (اطلاعات بیشتر )
dotnet ef --startup-project ../Core1RtmEmptyTest/ migrations add InitialDatabase
"dependencies": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.1.0-preview4-final",
"imports": [
"portable-net45+win8"
],
"type": "build"
},
// the rest ...
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.1.0-preview4-final",
"imports": [
"portable-net45+win8"
]
},
// the rest ...
} %UserProfile%\.nuget\packages\Microsoft.EntityFrameworkCore.Tools\1.1.0-preview4-final\tools
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
},
"imports": [
"dnxcore50",
"portable-net45+win8"
]
}
} error MSB4006: There is a circular dependency in the target dependency graph involving target "GetEFProjectMetadata"
dotnet new classlib c1
dotnet add reference ../c1/c1.csproj
<ItemGroup>
<ProjectReference Include="..\c1\c1.csproj" />
</ItemGroup> dotnet new sln
>dotnet sln add mymvc/mymvc.csproj Project `mymvc\mymvc.csproj` added to the solution. >dotnet sln add models/models.csproj Project `models\models.csproj` added to the solution.
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup> Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
return new ApplicationDbContext(siteSettings, httpContextAccessor, hostingEnvironment, logger);
}
} public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
public MyDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<MyDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new MyDbContext(builder.Options);
}
} For /F "delims=" %%G in (vscode-exts.txt) do code --install-extension %%G
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
public ApplicationDbContext(DbContextOptions options) : base(options)
{
} dotnet ef --startup-project ../MohasebKhodro/ migrations add InitialDatabase
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("Users")]
public class User : BaseEntity
{
public long Id { get; set; }
[Required]
public string FullName { get; set; } = null!;
} using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
namespace ProjectName.Common.EfHelpers;
public static class EfToolkit
{
/// <summary>
/// ایجاد نام موجودیتها
/// نام موجودیت اگر اتریبیوت تیبل داشته باشد
/// از همان نام استفاده میشود و اگر نداشته باشد
/// نامش جمع بسته میشود
/// </summary>
/// <param name="builder"></param>
public static void MakeTableNamesPluralized(this ModelBuilder builder)
{
var entityTypes = builder.Model.GetEntityTypes();
foreach (var entityType in entityTypes)
{
// Get the CLR type of the entity
var entityClrType = entityType.ClrType;
var hasTableAttribute = entityClrType.GetCustomAttribute<TableAttribute>();
// Apply the pluralized table name for the entity
if (hasTableAttribute is null)
{
// Get the pluralized table name
var pluralizedTableName = GetPluralizedTableName(entityClrType);
builder.Entity(entityClrType).ToTable(pluralizedTableName);
}
}
}
/// <summary>
/// گرفتن نام تایپ و عوض کردن نام آن از مفرد به جمع
/// Singular to plural
/// Category => Categories
/// Box => Boxes
/// Bus => Buses
/// Computer => Computers
/// </summary>
/// <param name="entityClrType"></param>
/// <returns></returns>
private static string GetPluralizedTableName(Type entityClrType)
{
// Example implementation (Note: This is a simple pluralization logic and might not cover all cases)
var typeName = entityClrType.Name;
if (typeName.EndsWith("y"))
{
// Substring(0, typeName.Length - 1)
// Range indexer
var typeNameWithoutY = typeName[..^1];
return typeNameWithoutY + "ies";
}
if (typeName.EndsWith("s") || typeName.EndsWith("x"))
{
return typeName + "es";
}
return typeName + "s";
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
// it should be placed here, otherwise it will rewrite the following settings!
base.OnModelCreating(builder);
builder.RegisterAllEntities(typeof(BaseEntity));
builder.MakeTableNamesPluralized();
builder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
} public static class EfToolkit
{
/// <summary>
/// ثبت تمامی انتیتیها
/// <param name="builder"></param>
/// <param name="type"></param>
/// </summary>
public static void RegisterAllEntities(this ModelBuilder builder, Type type)
{
var entities = type.Assembly.GetTypes()
.Where(x => x.BaseType == type);
foreach (var entity in entities)
builder.Entity(entity);
}
}