[英]An exception of type 'System.InvalidCastException' occurred in EntityFramework.Core.dll but was not handled in user code
I am trying to get the long
value associated to an ActivityLogType
it is associated to either a create
, edit
, and delete
record in the database. 我试图获取与ActivityLogType
相关联的long
值,它与数据库中的create
, edit
和delete
记录相关联。
It is used for an audit / activity log that is needed. 它用于所需的审计/活动日志。
public enum ActivityLogType
{
Create = 1,
Update = 2,
Delete = 3
}
My getter method: 我的getter方法:
public ActivityType GetType(ActivityLogType type)
{
var id = (long)type;
Console.WriteLine(id); // <---- this produces a 1 in the console. So the cast works?
return _context.ActivityTypes.Where(x => x.Id == id).FirstOrDefault(); // <-- This line throws the error
}
UPDATE 1 更新1
un-lucky suggested using (long)ActivityLogType.Create
to get the desired output. un-lucky建议使用(long)ActivityLogType.Create
来获得所需的输出。 I tried this: (Still not working) 我试过这个:(仍然没有工作)
public ActivityType GetType(ActivityLogType type)
{
switch (type)
{
case ActivityLogType.Create:
return _context.ActivityTypes.Where(x => x.Id == (long)ActivityLogType.Create).FirstOrDefault();
case ActivityLogType.Update:
return _context.ActivityTypes.Where(x => x.Id == (long)ActivityLogType.Update).FirstOrDefault();
case ActivityLogType.Delete:
return _context.ActivityTypes.Where(x => x.Id == (long)ActivityLogType.Delete).FirstOrDefault();
default:
return null;
}
}
UPDATE 2 更新2
Here is the ActivityType
entity 这是ActivityType
实体
public class ActivityType
{
public ActivityType()
{
this.Activities = new HashSet<Activity>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Display(Name = "Label")]
public string Label { get; set; }
[Display(Name = "Display Order")]
public int Order { get; set; }
[Display(Name = "Is Active")]
public bool IsActive { get; set; }
[Display(Name = "Activities")]
public virtual ICollection<Activity> Activities { get; set; }
}
你可以试试这个:
long id= Int64.Parse(Convert.ChangeType(type, Enum.GetUnderlyingType(type.GetType())).ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.