Is it possible to use the Entity Framework 6 with the code first pattern and write the models in C# and in IronPython?
The background is, that a few standard models are defined in the c# core, and some custom models has to be defined in IronPython.
EDIT
The custom models were defined in our productive systems for customization. The models should be loaded and added to the DbContext
at application startup. Every model is one IronPython file/module and will be loaded from a database (as all other scripts will be).
Not working sample
Program.cs
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IronPython_EF
{
class Program
{
// Private Member
private static SampleContext context;
static void Main(string[] args)
{
// Setup EntityFramework
context = new SampleContext();
// Create IronPython
var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = runtime.GetEngine("IronPython");
var scriptScope = engine.CreateScope();
// Set global var
scriptScope.SetVariable("DBContext", context);
// Load Model
ScriptSource modelSource = engine.CreateScriptSourceFromFile("Python\\User.py");
modelSource.Execute(scriptScope);
ScriptSource scriptSource = engine.CreateScriptSourceFromFile("Python\\Demo.py");
scriptSource.Execute(scriptScope);
// Prevent from exiting
Console.ReadLine();
}
}
}
SampleContext.cs
namespace IronPython_EF
{
using System;
using System.Data.Entity;
using System.Linq;
public class SampleContext : DbContext
{
public SampleContext() : base("name=SampleContext")
{
}
}
}
User.Py
# -----------------------------------------------
# Containing the UserModel
# -----------------------------------------------
# -----------------------------------------------
# Import
from System import Console
# -----------------------------------------------
#
class User(object):
userId = 0
userName = ""
def __init__(self):
pass
def get_userId(self):
return self.userId;
def set_userId(self, value):
self.userId = value
def get_userName(self):
return self.userName;
def set_userId(self, value):
self.userName = value
UserId = property(get_userId, set_userId)
UserName = property(get_userName, set_userId)
Demo.py
# -----------------------------------------------
# Demo Python Script, executing something in the
# Sample-DB-Context
# -----------------------------------------------
# -----------------------------------------------
# Import
from System import Console
# -----------------------------------------------
#
Console.WriteLine("Executing demo.py")
# Add User-Model
userSet = DBContext.Set[User]()
# Add User instance
usr = User()
usr.UserName = "Hallo Welt"
userSet.Add(usr)
# Save changes
DBContext.SaveChanges()
I get the exception, that User
is not part of the DBContext.
Thank you for your help!