简体   繁体   中英

Entity Framework Db First and Enum

I have Northwind db of Microsoft with table Orders:

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. 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. Should I make inheritance from Order class or there is some more clean way for this?

Add a partial class under the same namespace as the Order class (with the same name) and add your property there:

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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