简体   繁体   English

实体框架Db First和Enum

[英]Entity Framework Db First and Enum

I have Northwind db of Microsoft with table Orders: 我使用表Orders拥有Microsoft的Northwind数据库:

CREATE TABLE "Orders" (
    "OrderID" "int" IDENTITY (1, 1) NOT NULL ,
    "CustomerID" nchar (5) NULL ,
    "EmployeeID" "int" NULL ,
    "OrderDate" "datetime" NULL ,
    "RequiredDate" "datetime" NULL ,
    "ShippedDate" "datetime" NULL ,
    "ShipVia" "int" NULL ,
    "Freight" "money" NULL CONSTRAINT "DF_Orders_Freight" DEFAULT (0),
    "ShipName" nvarchar (40) NULL ,
    "ShipAddress" nvarchar (60) NULL ,
    "ShipCity" nvarchar (15) NULL ,
    "ShipRegion" nvarchar (15) NULL ,
    "ShipPostalCode" nvarchar (10) NULL ,
    "ShipCountry" nvarchar (15) NULL ,
    CONSTRAINT "PK_Orders" PRIMARY KEY  CLUSTERED 
    (
        "OrderID"
    ),
    CONSTRAINT "FK_Orders_Customers" FOREIGN KEY 
    (
        "CustomerID"
    ) REFERENCES "dbo"."Customers" (
        "CustomerID"
    ),
    CONSTRAINT "FK_Orders_Employees" FOREIGN KEY 
    (
        "EmployeeID"
    ) REFERENCES "dbo"."Employees" (
        "EmployeeID"
    ),
    CONSTRAINT "FK_Orders_Shippers" FOREIGN KEY 
    (
        "ShipVia"
    ) REFERENCES "dbo"."Shippers" (
        "ShipperID"
    )
)

I want to working with this db by Entity Framework. 我想通过实体框架使用此数据库。 For that, I create edmx-model for existed db. 为此,我为现有数据库创建edmx-model。 Now I want to add enum property Status, which should be calculated by DateTime.Now, OrderDate, RequiredDate, etc, but I don't know how to add this property to Order class, whithout changing Orders table. 现在,我想添加枚举属性Status,该属性应该由DateTime.Now,OrderDate,RequiredDate等计算,但是我不知道如何在不更改Orders表的情况下将该属性添加到Order类。 Should I make inheritance from Order class or there is some more clean way for this? 我应该继承Order类还是有一些更简洁的方法?

Add a partial class under the same namespace as the Order class (with the same name) and add your property there: 在与Order类相同的名称空间下添加一个局部类(具有相同的名称),然后在其中添加属性:

public partial class Order
{
     public SomeStatusEnum Status
     {
          get { //Put your code to figure out the enum here. }
     }
}

This works because the classes generated by the EF are partial for precisely this reason. 这样做是因为正是由于这个原因,EF生成的类是局部的。

One common situation you may encounter with this approach is that you will get an error if you simply try to add the class. 使用此方法可能会遇到的一种常见情况是,如果您只是尝试添加类,则会出现错误。 This is because the EDMX model will create a file under the covers with the same name of the class. 这是因为EDMX模型将在幕后使用该类的相同名称创建一个文件。 You can find this file if you traverse the files added by the designer. 如果遍历设计者添加的文件,则可以找到此文件。 To get around this, create a folder (eg POCOs) and put your class in there, then change the namespace to match that of the EDMX classes. 为了解决这个问题,创建一个文件夹(例如POCO)并将您的类放在其中,然后更改名称空间以匹配EDMX类的名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM