When using linqtosql, we can easily set the int field type of an object in the model to the User-Defined Enumeration type.
However, in EF, I do not know why Microsoft did not directly provide the setting method. After exploration, we can find that the following code can be modified to perfectly implement the field type of the object in EF.
Set to Enumeration type.
1. Modify the public keyword of the customer attribute customertype to private (note: the code here is automatically generated by ef. You only need to modify the public key)
Code
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
private int CustomerType
{
get
{
return this._CustomerType;
}
set
{
this.OnCustomerTypeChanging(value);
this.ReportPropertyChanging("CustomerType");
this._CustomerType = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("CustomerType");
this.OnCustomerTypeChanged();
}
}
2. manually create the customer partial class to replace the EF mertype attribute generated by EF with mermertype_new
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EFEnum
{
public partial class Customer
{
public CustomerType CustomerType_New
{
get { return (CustomerType)CustomerType; }
set { CustomerType = (int)value; }
}
}
}
3. Call
Code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace efenum
{
Class Program
{
Static void main (string [] ARGs)
{
Using (testentities T = new testentities ())
{
// Call the modified EF model
Foreach (var u in T. Customer)
{
Console. writeline (string. Format ("customername: [{0}] customertype: [{1}]", U. customername, U. customertype_new ));
}
Console. readkey ();
}
}
}
/// <Summary>
/// Customer ing the mertype attribute of the customer class to Enumeration
/// </Summary>
Public Enum customertype
{
/// <Summary>
/// Transaction customer
/// </Summary>
Trader,
/// <Summary>
/// Supplier
/// </Summary>
Supplier
}
}
Call result: