定义一种用于引用2个不同实体的通用变量

时间:2015-08-17 08:55:34

标签: c# .net asp.net-mvc entity-framework generics

我有一些具有相同属性的模型类(@echo off :: script for updating property files SETLOCAL EnableExtensions SETLOCAL EnableDelayedExpansion if "%3"=="" ( ECHO Script will optionally accept 3 args: PropKey PropVal File SET PROPKEY=Deviceid SET PROPVAL=dfs2341f SET FILE=config.properties ) ELSE ( SET PROPKEY=%1 SET PROPVAL=%2 SET FILE=%3 ) FINDSTR /B %PROPKEY% %FILE% >nul IF %ERRORLEVEL% EQU 1 GOTO nowork MOVE /Y "%FILE%" "%FILE%.bak" FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%FILE%.bak" ^|FIND /N /I "%PROPKEY%"`) DO ( SET LINE=%%A ) FOR /F "tokens=1,2* delims=]" %%S in ("%LINE%") DO SET LINE=%%S SET /A LINE=%LINE:~1,6% SET /A COUNT=1 FOR /F "USEBACKQ tokens=*" %%A IN (`FIND /V "" ^<"%FILE%.bak"`) DO ( IF "!COUNT!" NEQ "%LINE%" ( ECHO %%A>>"%FILE%" ) ELSE ( ECHO %PROPKEY%=%PROPVAL%>>"%FILE%" ECHO Updated %FILE% with value %PROPKEY%=%PROPVAL% ) SET /A COUNT+=1 ) GOTO end :nowork echo Didn't find matching string %PROPKEY% in %FILE%. No work to do. pause :end &amp; RevisedDate):

RevisedBy

现在我有以下代码:

public class Request
{
    public int RequestId { get; set; }
    ...
    public DateTime RevisedDate { get; set; } <---
    public User RevisedBy { get; set; }       <---
}

public class Material
{
    public int MaterialId { get; set; }
    ...
    public DateTime RevisedDate { get; set; } <---
    public User RevisedBy { get; set; }       <---
}

我的问题:是否可以汇编这两个代码并执行这样的通用代码:

if (entry.Entity is Request)
{
    Request request = (Request)entry.Entity;
    ctx.LoadProperty(request.RevisedBy, x => x.Roles);
    if (request.RevisedBy.Roles.Find(x => x.RoleName == "ADMIN") == null) return;
}

if (entry.Entity is Material)
{
    Material material = (Material)entry.Entity;
    ctx.LoadProperty(material.RevisedBy, x => x.Roles);
    if (material.RevisedBy.Roles.Find(x => x.RoleName == "ADMIN") == null) return;
}

2 个答案:

答案 0 :(得分:3)

添加一个界面,用于定义&#34; Revisable&#34;合同。然后让类实现这个接口

public interface IRevisable
{
   DateTime RevisedDate { get; set; }
   User RevisedBy { get; set; }    
}


public class Request: IRevisable
{
}

public class Material: IRevisable
{
}

然后

if (entry.Entity is IRevisable)
{
     var myEntity = entry.Entity as IRevisable;
     ctx.LoadProperty(myEntity.RevisedBy, x => x.Roles);
     if (myEntity.RevisedBy.Roles.Find(x => x.RoleName == "ADMIN") == null)    return;
}

答案 1 :(得分:0)

您绝对可以从某种BaseEntity类继承您的类:

public class BaseEntity 
{
    ...
    public DateTime RevisedDate { get; set; } <---
    public User RevisedBy { get; set; }       <---
}


public class Request: BaseEntity 
{
    ...
}

public class Material: BaseEntity 
{
    ...
}

然后你可以这样做:

if (entry.Entity is BaseEntity)
{
   ... // your stuff
}