CodeFirst-Section1之小例子

本文介绍如何使用Entity Framework (EF) 的CodeFirst方法从C#类生成数据库。通过具体实例展示了领域驱动设计(DDD)思想的应用,并提供了创建数据库上下文类、配置连接字符串及执行数据库操作的完整步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

尽可能做到不说一些晦涩难懂的语言,Follow Me......

环境:Visual Studio 2013+.Net Framework 4.5

1.什么是Code First?

说白了就是先建好C#类,利用EF数据库上下文去生成数据库和数据,从数据库驱动的思想转变为代码驱动

Code First主要使用DDD领域驱动设计思想

废话也不多说了......

2.安装EF:

3.新建类

公司

    public class Company
    {
        public string CompanyId { get; set; }
        public string CompanyName { get; set; }
        public ICollection<Department> Departments { get; set; }
    }

 

 部门

    public class Department
    {
        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    }

 

 现在,领域类我们已经创建完毕,接下来创建DbContext

    public class DemoContext : DbContext
    {
        public DemoContext() : base("name=DemoContext") { }
        public DbSet<Company> Companys { get; set; }
        public DbSet<Department> Departments { get; set; }
    }

 

 接着配置config连接字符串回到主程序

<add name="DemoContext" connectionString="server=.;uid=sa;pwd=1230;database=CodeFirst" providerName="System.Data.SqlClient"/>

 这里记得字符串中一定要有providerName

回到主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirst_Section1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new DemoContext())
            {
                Company compay = new Company
                {
                    CompanyName = "南京某某科技有限公司"
                };
                db.Companys.Add(compay);
                db.SaveChanges();
            }
            Console.ReadKey();
        }
    }
}

 查看数据库生成的表结构

End.

 

转载于:https://www.cnblogs.com/hexd1230/p/5977061.html

我正在学习NX二次开发,用的是Visual Studio 2019,ug版本是12.0,开发平台是c++,uf函数为主nxopen函数为辅。需要你辅助我开发,重点注意开发模版是c++,优先使用uf函数,要求你先搞清楚你提供给我的代码真实有效性,语句与标点符号的正确位置,避免出现ug12.0没有提供的接口成员出现!确保所有方法调用都符合 NX12 的 API 签名,深度思考下再回答,每次回答前先回顾下前面的所有对话避免问题重复出现,每行代码都用中文注解具体意思与作用。//============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\NXopen\BaiduSyncdisk\studio\hkjm\ui\hkjm.cpp // // This file was generated by the NX Block UI Styler // Created by: MiCH-CEO // Version: NX 12 // Date: 08-06-2025 (Format: mm-dd-yyyy) // Time: 19:18 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C++ source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ //These includes are needed for the following template code //------------------------------------------------------------------------------ #include "hkjm.hpp" using namespace NXOpen; using namespace NXOpen::BlockStyler; //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session *(hkjm::theSession) = NULL; UI *(hkjm::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ hkjm::hkjm() { try { // Initialize the NX Open C++ API environment hkjm::theSession = NXOpen::Session::GetSession(); hkjm::theUI = UI::GetUI(); theDlxFileName = "hkjm.dlx"; theDialog = hkjm::theUI->CreateDialog(theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &hkjm::apply_cb)); theDialog->AddOkHandler(make_callback(this, &hkjm::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &hkjm::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &hkjm::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &hkjm::dialogShown_cb)); } catch(exception& ex) { //---- Enter your exception handling code here ----- throw; } } //------------------------------------------------------------------------------ // Destructor for NX Styler class //------------------------------------------------------------------------------ hkjm::~hkjm() { if (theDialog != NULL) { delete theDialog; theDialog = NULL; } } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char *param, int *retcod, int param_len) { hkjm *thehkjm = NULL; try { UF_initialize(); //开发的许可函数,初始化 thehkjm = new hkjm(); // The following method shows the dialog immediately thehkjm->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if(thehkjm != NULL) { delete thehkjm; thehkjm = NULL; }UF_terminate(); //释放许可函数,结束化 } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } int hkjm::Show() { try { theDialog->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ void hkjm::initialize_cb() { try { group0 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group0")); hk2edge = dynamic_cast<NXOpen::BlockStyler::CurveCollector*>(theDialog->TopBlock()->FindBlock("hk2edge")); hk1edge = dynamic_cast<NXOpen::BlockStyler::CurveCollector*>(theDialog->TopBlock()->FindBlock("hk1edge")); hk1sd = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("hk1sd")); hk2sd = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("hk2sd")); group = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group")); hkdj = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("hkdj")); hk2jd = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("hk2jd")); hk1jd = dynamic_cast<NXOpen::BlockStyler::ExpressionBlock*>(theDialog->TopBlock()->FindBlock("hk1jd")); vector0 = dynamic_cast<NXOpen::BlockStyler::SpecifyVector*>(theDialog->TopBlock()->FindBlock("vector0")); bodySelect0 = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("bodySelect0")); color1 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("color1")); color2 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("color2")); } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any value set //here will take precedence and dialog will be launched showing that value. //------------------------------------------------------------------------------ void hkjm::dialogShown_cb() { try { //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ // 应用按钮回调函数 - 读取所有控件数据 int hkjm::apply_cb() { int errorCode = 0; // 错误代码,0表示成功 // 声明变量存储所有控件值 std::vector<NXOpen::Curve*> sectionCurves1; std::vector<NXOpen::Curve*> sectionCurves2; double hk1sdValue = 0.0; double hk2sdValue = 0.0; double hkdjValue = 0.0; double hk1jdValue = 0.0; double hk2jdValue = 0.0; NXOpen::Vector3d directionVector(0.0, 0.0, 1.0); std::vector<NXOpen::Body*> selectedBodies; int colorIndex1 = 0; int colorIndex2 = 0; try { // 获取NX会话和工作部件 NXOpen::Session* theSession = NXOpen::Session::GetSession(); NXOpen::Part* workPart = theSession->Parts()->Work(); NXOpen::UI* theUI = NXOpen::UI::GetUI(); // ===== 1. 处理曲线选择器1的值 ===== if (hk1edge) // 检查曲线选择器1控件是否有效 { // 获取曲线选择器1的属性列表 (使用BlockStyler命名空间) NXOpen::BlockStyler::PropertyList* props = hk1edge->GetProperties(); // 获取选中的曲线对象集合 std::vector<NXOpen::TaggedObject*> selObjs = props->GetTaggedObjectVector("SelectedObjects"); // 遍历所有选中的对象 for (NXOpen::TaggedObject* obj : selObjs) { // 将对象转换为曲线类型 if (NXOpen::Curve* curve = dynamic_cast<NXOpen::Curve*>(obj)) { sectionCurves1.push_back(curve); } } // 释放属性列表内存 delete props; } // ===== 2. 处理曲线选择器2的值 ===== if (hk2edge) // 检查曲线选择器2控件是否有效 { // 获取曲线选择器2的属性列表 NXOpen::BlockStyler::PropertyList* props = hk2edge->GetProperties(); // 获取选中的曲线对象集合 std::vector<NXOpen::TaggedObject*> selObjs = props->GetTaggedObjectVector("SelectedObjects"); // 遍历所有选中的对象 for (NXOpen::TaggedObject* obj : selObjs) { // 将对象转换为曲线类型 if (NXOpen::Curve* curve = dynamic_cast<NXOpen::Curve*>(obj)) { sectionCurves2.push_back(curve); } } // 释放属性列表内存 delete props; } // ===== 3. 获取hk1sd表达式值 ===== if (hk1sd) // 检查表达式控件是否有效 { // 获取表达式控件的属性列表 NXOpen::BlockStyler::PropertyList* props = hk1sd->GetProperties(); // 获取表达式的当前值 hk1sdValue = props->GetDouble("Value"); // 释放属性列表内存 delete props; } // ===== 4. 获取hk2sd表达式值 ===== if (hk2sd) // 检查表达式控件是否有效 { // 获取表达式控件的属性列表 NXOpen::BlockStyler::PropertyList* props = hk2sd->GetProperties(); // 获取表达式的当前值 hk2sdValue = props->GetDouble("Value"); // 释放属性列表内存 delete props; } // ===== 5. 获取hkdj表达式值 ===== if (hkdj) // 检查表达式控件是否有效 { // 获取表达式控件的属性列表 NXOpen::BlockStyler::PropertyList* props = hkdj->GetProperties(); // 获取表达式的当前值 hkdjValue = props->GetDouble("Value"); // 释放属性列表内存 delete props; } // ===== 6. 获取hk1jd表达式值 ===== if (hk1jd) // 检查表达式控件是否有效 { // 获取表达式控件的属性列表 NXOpen::BlockStyler::PropertyList* props = hk1jd->GetProperties(); // 获取表达式的当前值 hk1jdValue = props->GetDouble("Value"); // 释放属性列表内存 delete props; } // ===== 7. 获取hk2jd表达式值 ===== if (hk2jd) // 检查表达式控件是否有效 { // 获取表达式控件的属性列表 NXOpen::BlockStyler::PropertyList* props = hk2jd->GetProperties(); // 获取表达式的当前值 hk2jdValue = props->GetDouble("Value"); // 释放属性列表内存 delete props; } // ===== 8. 获取矢量方向 ===== if (vector0) // 检查矢量控件是否有效 { // 获取矢量控件的属性列表 NXOpen::BlockStyler::PropertyList* props = vector0->GetProperties(); // 获取矢量方向 directionVector = props->GetVector("Vector"); // 释放属性列表内存 delete props; } // ===== 9. 处理选中的实体 ===== if (bodySelect0) // 检查实体选择器控件是否有效 { // 获取实体选择器的属性列表 NXOpen::BlockStyler::PropertyList* props = bodySelect0->GetProperties(); // 获取选中的实体对象集合 std::vector<NXOpen::TaggedObject*> selObjs = props->GetTaggedObjectVector("SelectedObjects"); // 遍历所有选中的对象 for (NXOpen::TaggedObject* obj : selObjs) { // 将对象转换为实体类型 if (NXOpen::Body* body = dynamic_cast<NXOpen::Body*>(obj)) { selectedBodies.push_back(body); } } // 释放属性列表内存 delete props; } // ===== 10. 获取颜色选择器1的颜色 ===== if (color1) // 检查颜色选择器控件是否有效 { // 获取颜色选择器的属性列表 NXOpen::BlockStyler::PropertyList* colorProps = color1->GetProperties(); // 获取颜色值(整数向量) std::vector<int> colors = colorProps->GetIntegerVector("Value"); // 获取第一个颜色索引值 if (!colors.empty()) { colorIndex1 = colors[0]; } // 释放属性列表内存 delete colorProps; } // ===== 11. 获取颜色选择器2的颜色 ===== if (color2) // 检查颜色选择器控件是否有效 { // 获取颜色选择器的属性列表 NXOpen::BlockStyler::PropertyList* colorProps = color2->GetProperties(); // 获取颜色值(整数向量) std::vector<int> colors = colorProps->GetIntegerVector("Value"); // 获取第一个颜色索引值 if (!colors.empty()) { colorIndex2 = colors[0]; } // 释放属性列表内存 delete colorProps; } // ===== 执行拉伸操作 ===== if (!sectionCurves1.empty() && hk1sdValue != 0.0) { // 设置撤销标记 NXOpen::Session::UndoMarkId markId = theSession->SetUndoMark( NXOpen::Session::MarkVisibilityVisible, "拉伸操作"); // 创建拉伸构建器 NXOpen::Features::ExtrudeBuilder* extrudeBuilder = workPart->Features()->CreateExtrudeBuilder(nullptr); // 创建截面对象 NXOpen::Section* section = workPart->Sections()->CreateSection( 0.001, 0.001, 0.05); extrudeBuilder->SetSection(section); // 添加曲线到截面 (NX 12兼容方法) for (NXOpen::Curve* curve : sectionCurves1) { // 创建曲线规则 - 使用CreateRuleCurveFeature std::vector<NXOpen::Curve*> curveVec(1, curve); NXOpen::SelectionIntentRule* curveRule = workPart->ScRuleFactory()->CreateRuleCurveFeature( curveVec, true); // 允许特征曲线 // 获取曲线上的点 NXOpen::Point3d pointOnCurve; curve->EvaluatePoint(0.5, pointOnCurve); // 添加到截面 (NX 12兼容参数) section->AddToSection( curveRule, // 选择规则 curve, // 曲线对象 nullptr, // 无基准点 nullptr, // 无基准方向 pointOnCurve, // 曲线上的点 NXOpen::Section::ModeCreate, false // 不反转方向 ); } // 设置拉伸方向 (NX 12兼容方法) NXOpen::Point3d origin(0.0, 0.0, 0.0); NXOpen::Direction* extrudeDirection = workPart->Directions()->CreateDirection( origin, // 原点 directionVector, // 方向向量 NXOpen::SmartObject::UpdateOptionWithinModeling ); extrudeBuilder->SetDirection(extrudeDirection); // 设置拉伸范围 (NX 12兼容方法) NXOpen::GeometricUtilities::Limits* limits = extrudeBuilder->Limits(); limits->StartExtend()->Value()->SetRightHandSide("0"); limits->EndExtend()->Value()->SetRightHandSide( std::to_string(hk1sdValue).c_str()); // 设置布尔操作类型(创建新实体) extrudeBuilder->BooleanOperation()->SetType( NXOpen::GeometricUtilities::BooleanOperation::BooleanTypeCreate); // 设置拔模角度 (NX 12兼容方法) if (hk1jdValue != 0.0) { extrudeBuilder->Draft()->FrontDraftAngle()->SetRightHandSide( std::to_string(hk1jdValue).c_str()); } // 设置偏置参数 (NX 12兼容方法) if (hk2sdValue != 0.0) { extrudeBuilder->Offset()->StartOffset()->SetRightHandSide("0"); extrudeBuilder->Offset()->EndOffset()->SetRightHandSide( std::to_string(hk2sdValue).c_str()); } // 执行拉伸操作 NXOpen::NXObject* featureNXObject = extrudeBuilder->Commit(); NXOpen::Features::Feature* feature = dynamic_cast<NXOpen::Features::Feature*>(featureNXObject); // 获取特征创建的实体 std::vector<NXOpen::Body*> featureBodies; if (feature) { feature->GetBodies(featureBodies); } if (!featureBodies.empty() && colorIndex1 != 0) { // 设置新创建实体的颜色 UF_OBJ_set_color(featureBodies[0]->Tag(), colorIndex1); } // 清理资源 extrudeBuilder->Destroy(); section->Destroy(); } } catch (std::exception& ex) { errorCode = 1; NXOpen::Session* theSession = NXOpen::Session::GetSession(); theSession->NXMessageBox()->Show("错误", NXOpen::NXMessageBox::DialogTypeError, ("操作失败: " + std::string(ex.what())).c_str()); } catch (...) { errorCode = 1; NXOpen::Session* theSession = NXOpen::Session::GetSession(); theSession->NXMessageBox()->Show("错误", NXOpen::NXMessageBox::DialogTypeError, "未知操作错误"); } return errorCode; } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ int hkjm::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { if(block == hk2edge) { //---------Enter your code here----------- } else if(block == hk1edge) { //---------Enter your code here----------- } else if(block == hk1sd) { //---------Enter your code here----------- } else if(block == hk2sd) { //---------Enter your code here----------- } else if(block == hkdj) { //---------Enter your code here----------- } else if(block == hk2jd) { //---------Enter your code here----------- } else if(block == hk1jd) { //---------Enter your code here----------- } else if(block == vector0) { //---------Enter your code here----------- } else if(block == bodySelect0) { //---------Enter your code here----------- } else if(block == color1) { //---------Enter your code here----------- } else if(block == color2) { //---------Enter your code here----------- } } catch(exception& ex) { //---- Enter your exception handling code here ----- hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ int hkjm::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); } catch(exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; hkjm::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Description: Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ PropertyList* hkjm::GetBlockProperties(const char *blockID) { return theDialog->GetBlockProperties(blockID); } 以上代码拉伸部分报错:严重性 代码 说明 项目 文件 行 禁止显示状态 错误(活动) E0304 没有与参数列表匹配的 重载函数 "NXOpen::Section::AddToSection" 实例 hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 468 错误(活动) E0304 没有与参数列表匹配的 重载函数 "NXOpen::ScRuleFactory::CreateRuleCurveFeature" 实例 hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 459 错误(活动) E0135 class "NXOpen::Curve" 没有成员 "EvaluatePoint" hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 465 错误(活动) E0135 class "NXOpen::Features::Feature" 没有成员 "GetBodies" hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 520 错误(活动) E0135 class "NXOpen::Session" 没有成员 "NXMessageBox" hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 537 错误(活动) E0135 class "NXOpen::Session" 没有成员 "NXMessageBox" hkjm D:\NXopen\BaiduSyncdisk\studio\hkjm\hkjm.cpp 545
08-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值