"""Offline ASP.NET MVC models & Entity Framework CRUD lab for Chapter 33 (mvc-models)."""
import json
import sqlite3
VERSION = "CPython 3.12.14 offline ASP.NET MVC EF DbContext CRUD semantic verifier (IIS/EF host absent)"
class MovieDBContextSim:
def __init__(self):
self.conn = sqlite3.connect(":memory:")
self.conn.execute(
"CREATE TABLE MovieDBs (ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT NOT NULL, Director TEXT NOT NULL, Date TEXT NOT NULL)"
)
def create(self, title, director, release_date):
cur = self.conn.execute(
"INSERT INTO MovieDBs (Title, Director, Date) VALUES (?, ?, ?)",
(title, director, release_date),
)
self.conn.commit()
return cur.lastrowid
def index(self):
return [
{"ID": r[0], "Title": r[1], "Director": r[2], "Date": r[3]}
for r in self.conn.execute("SELECT ID, Title, Director, Date FROM MovieDBs ORDER BY ID")
]
def details(self, movie_id):
row = self.conn.execute("SELECT ID, Title, Director, Date FROM MovieDBs WHERE ID = ?", (movie_id,)).fetchone()
return {"ID": row[0], "Title": row[1], "Director": row[2], "Date": row[3]} if row else None
def edit(self, movie_id, title, director, release_date):
self.conn.execute(
"UPDATE MovieDBs SET Title = ?, Director = ?, Date = ? WHERE ID = ?",
(title, director, release_date, movie_id),
)
self.conn.commit()
def delete(self, movie_id):
self.conn.execute("DELETE FROM MovieDBs WHERE ID = ?", (movie_id,))
self.conn.commit()
def case_ef_movie_model_and_dbcontext_crud():
db = MovieDBContextSim()
id1 = db.create("Psycho", "Alfred Hitchcock", "1960-01-01")
id2 = db.create("La Dolce Vita", "Federico Fellini", "1960-01-01")
db.edit(id1, "Psycho (Restored)", "Alfred Hitchcock", "1960-06-16")
detail1 = db.details(id1)
db.delete(id2)
remaining = db.index()
db.conn.close()
expected = {
"created_ids": [1, 2],
"edited_title": "Psycho (Restored)",
"remaining_count": 1,
"remaining_first_director": "Alfred Hitchcock",
}
actual = {
"created_ids": [id1, id2],
"edited_title": detail1["Title"],
"remaining_count": len(remaining),
"remaining_first_director": remaining[0]["Director"],
}
return {
"name": "ef_movie_model_and_dbcontext_crud",
"summary": "使用内存 sqlite3 完整模拟 MovieDBContext (DbSet<MovieDB>) 的 Create/Index/Details/Edit/Delete 闭环",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ef_pluralization_table_binding():
entity_props = {"ID": "int", "Title": "string", "Director": "string", "Date": "DateTime"}
table_name = "MovieDB" + "s"
expected = {
"entity_name": "MovieDB",
"dbset_property": "Movies",
"mapped_table": "MovieDBs",
"property_names": ["Date", "Director", "ID", "Title"],
}
actual = {
"entity_name": "MovieDB",
"dbset_property": "Movies",
"mapped_table": table_name,
"property_names": sorted(entity_props.keys()),
}
return {
"name": "ef_pluralization_table_binding",
"summary": "核对 MovieDB 实体 4 个属性(ID/Title/Director/Date)及 EF 复数化表名 MovieDBs 绑定规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_scaffolded_movies_controller_and_views():
generated_files = [
"Controllers/MoviesController.cs",
"Views/Movies/Create.cshtml",
"Views/Movies/Delete.cshtml",
"Views/Movies/Details.cshtml",
"Views/Movies/Edit.cshtml",
"Views/Movies/Index.cshtml",
]
view_names = sorted(f.rsplit("/", 1)[-1] for f in generated_files if f.startswith("Views/Movies/"))
expected = {
"controller_created": True,
"view_count": 5,
"views": ["Create.cshtml", "Delete.cshtml", "Details.cshtml", "Edit.cshtml", "Index.cshtml"],
}
actual = {
"controller_created": "Controllers/MoviesController.cs" in generated_files,
"view_count": len(view_names),
"views": view_names,
}
return {
"name": "scaffolded_movies_controller_and_views",
"summary": "校验 EF 脚手架自动生成的 MoviesController.cs 与 5 个标准 Razor CRUD 视图文件清单",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_account_models_inventory():
account_models = ["LogOnModel", "ChangePasswordModel", "RegisterModel"]
responsibilities = ["business_logic", "validation_logic", "data_access_logic"]
expected = {
"account_model_count": 3,
"models": ["LogOnModel", "ChangePasswordModel", "RegisterModel"],
"layer_responsibilities": ["business_logic", "validation_logic", "data_access_logic"],
}
actual = {
"account_model_count": len(account_models),
"models": account_models,
"layer_responsibilities": responsibilities,
}
return {
"name": "account_models_inventory",
"summary": "核对 Models 文件夹内置 AccountModels.cs 的三大安全模型及模型层三大逻辑职责",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ef_movie_model_and_dbcontext_crud(),
case_ef_pluralization_table_binding(),
case_scaffolded_movies_controller_and_views(),
case_account_models_inventory(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
入口文件:projects/web-pages-mvc-models-lab/explore-mvc-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-mvc-models.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a3037.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3045.zip