无法隐式转换为BaseEntity <system.guid>

时间:2016-12-14 17:42:56

标签: c# asp.net-mvc asp.net-core guid

我正在制作一个带.net核心的mvc应用程序而且我被卡住了。在我的后台,由于guid问题,我的删除存在问题。我的变量'model'给出了问题:

无法将类型'Overnight.Models.Security.ApplicationRole'隐式转换为'Overnight.Models.BaseEntity'

我的RoleController.cs中的代码:

[HttpGet("[area]/[controller]/[action]/{id:Guid}")]
        public async Task<IActionResult> Delete(Guid id, [FromQuery] ActionType actionType)
        {
            var model = await ApplicationDbContext.Roles.FirstOrDefaultAsync(m => m.Id == id);

            if(model == null)
            {
                return RedirectToAction("Index");
            }

            var viewModel = new ActionRoleViewModel()
            {
                //error: Cannot implicitly convert type 'Overnight.Models.Security.ApplicationRole' to 'Overnight.Models.BaseEntity<System.Guid>'
                BaseEntity = model,
                ActionType = actionType
            };
            return View(viewModel);
        }

这是我的BaseEntity.cs:

namespace Overnight.Models
{
    public class BaseEntity<T> : IBaseEntity<T>
    {
        public T Id { get; set; }

        public DateTime CreatedAt { get; set; }
        public Nullable<DateTime> UpdatedAt { get; set; }
        public Nullable<DateTime> DeletedAt { get; set; }
    }
}

这是我的ActionRoleViewModel.cs:

namespace Overnight.Models.ViewModels
{
    public class ActionRoleViewModel : ActionBaseEntityViewModel<Guid>
    {
    }
}

这是我的ApplicationRole.cs:

namespace Overnight.Models.Security
{
    public class ApplicationRole : IdentityRole<Guid>
    {
        public DateTime CreatedAt {get; set;}
        public Nullable<DateTime> UpdatedAt {get; set;}
        public Nullable<DateTime> DeletedAt {get; set;}      
    }
}

我尝试制作不同的BaseEntities,我把Guid而不是T但是我一直有同样的错误

修改

这是我的ActionBaseEntityViewModel.cs:

namespace Overnight.Models.ViewModels
{
    public class ActionBaseEntityViewModel<T>: ActionViewModel
    {
        public BaseEntity<T> BaseEntity { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

问题就在于错误状态。您正尝试将ActionRoleViewModel.BaseEntity设置为ApplicationRole,但ApplicationRole不会从BaseEntity继承,因此它们不兼容。

您可以将ActionRoleViewModel.BaseEntity媒体资源修改为IBaseEntity<T>类型,并将界面添加到ApplicationRole。这将创建必要的继承。

所以你的ActionBaseEntityViewModel看起来像这样:

public class ActionBaseEntityViewModel<T>: ActionViewModel
{
    public IBaseEntity<T> BaseEntity { get; set; }
}

你的ApplicationRole看起来像这样:

public class ApplicationRole : IdentityRole<Guid>, IBaseEntity<Guid>
{
    public DateTime CreatedAt {get; set;}
    public Nullable<DateTime> UpdatedAt {get; set;}
    public Nullable<DateTime> DeletedAt {get; set;}      
}