When working with Entity Framework Core migration, I prefer separating Target project from Startup project.
The Startup project is a Console Application with the following snippet.
static void Main(string[] args)
{
// Needs a host
Host.CreateDefaultBuilder(args)
.ConfigureServices(svc =>
{
svc.AddDbContext<MyContext>(opt =>
{
opt.UseSqlServer(// other parameters go here
, _ => _.MigrationsAssembly(Assembly.GetAssembly(typeof(Dummy))!.GetName().Name));
});
})
.Build();
}
And the Target project is a Class Library project with a Dummy
class as follows.
public class Dummy
{
}
We can also make the Target project 100% empty but I have to change Assembly.GetAssembly(typeof(Dummy))!.GetName().Name
to a string literal "Target"
(assuming the Target project is named Target
).
Question
I am curious whether there is another elegant way (with neither dummy class nor string literal) to reference an empty Target project.
My repo maybe useful for testing rather than creating from zero.
CodePudding user response:
I'm not sure if it's elegant or bulletproof but you could search through all assemblies (AppDomain.CurrentDomain.GetAssemblies()
) for the one that has a class that derives from DbMigration
or DbContext
with the help of Type.IsAssignableFrom(Type) Method.
CodePudding user response:
I've used this code:
var targetAssembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(a => a.GetName().Name == "Assembly.Name");