无法从int转换为ApiModels.Enums.EnumStuff

时间:2015-06-05 18:22:42

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

它给出的两个错误是,无法从ApiModels.Enums.ContentAreaEnum转换为最佳重载方法匹配''有一些无效的参数我试图使用存储库,API模型和服务从数据库中显示一个简单的列表。我没有太多使用任何经验,所以我希望充分了解错误。

在我的索引中,我试图显示内容,但我收到了错误。

public ActionResult Index(int id)
{
    ViewData["Claims"] = _ctsService.GetClaimsForContentArea(id);
    return View();    
}

这是我引用的IService:

List<Claim> GetClaimsForContentArea(ContentAreaEnum contentArea);

服务:

public List<Claim> GetClaimsForContentArea(ContentAreaEnum contentArea)
{
    return _claimRepository.GetClaimsInContentArea((int)contentArea);
}

存储库:

public List<Claim> GetClaimsInContentArea(int contentAreaId)
{
    var query = from c in _db.Claims
            where c.ContentArea_ID == contentAreaId
            select c;

    return query.ToList();
}

IRepository:

List<Claim> GetClaimsInContentArea(int contentAreaId);

和ApiModel:

public enum ContentAreaEnum
{
    Subject1 = 1,
    Subject2 = 2
}

1 个答案:

答案 0 :(得分:1)

我相信你正在引用编译错误。

由于您的方法签名看起来像List<Claim> GetClaimsForContentArea(ContentAreaEnum contentArea);,并且您尝试将int传递给它,因此无效。

您必须将int转换为枚举或将枚举转换为int,如:

public ActionResult Index(int id)
{

    ViewData["Claims"] = _ctsService.GetClaimsForContentArea((ContentAreaEnum)id);
    return View();

}

但是你不需要另一个转换为int。我认为您应该将GetClaimsForContentArea()方法签名更改为GetClaimsForContentArea(int id)并将此参数转换为枚举,或者摆脱看似不必要的整个转换。

编辑:

如果您确实需要验证int id值,可以添加以下代码:

public ActionResult Index(int id)
{

    if(Enum.IsDefined(typeof(ContentAreaEnum), id)) {
       ViewData["Claims"] = _ctsService.GetClaimsForContentArea((ContentAreaEnum)id);
    }

    return View();

}