Ben*_*dEg 5 c# ironpython entity-framework dynamic-language-runtime sqlanywhere
是否可以将Entity Framework 6与代码第一模式一起使用,并在C#和IronPython中编写模型?
背景是,c#core中定义了一些标准模型,并且必须在IronPython中定义一些自定义模型.
编辑
定制模型在我们的定制生产系统中定义.应该加载模型并将其添加到DbContext应用程序启动时.每个模型都是一个IronPython文件/模块,将从数据库加载(与所有其他脚本一样).
不工作的样品
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
SampleContext.cs
namespace IronPython_EF
{
using System;
using System.Data.Entity;
using System.Linq;
public class SampleContext : DbContext
{
public SampleContext() : base("name=SampleContext")
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
我得到了异常,这User不是DBContext的一部分.
谢谢您的帮助!
我不确定这是否可能,因为 IronPython 类不是 .NET 类。可以编写一个自定义映射器,然后从 IronPython 文件为您生成类。但这可能会因关系/索引/键等而变得复杂。
如果您必须保留 IronPython,并且您正在寻找 EF 的 ORM 优势,那么替代方案是: http: //www.sqlalchemy.org/
但如果您正在寻找 EF 提供的其他优点(迁移等),那么这将是一个问题。