我正在尝试弄清楚如何在OData中使用 NotMapped 属性
我有用户模型:
[DataContract]
public class User
{
[DataMember]
public long Id { get; set; }
[DataMember]
public virtual InstagramUser InstagramUser { get; set; }
[DataMember]
public virtual FacebookUser FacebookUser { get; set; }
[NotMapped]
public string InstagramID { get; set;
}
我在用户控制器中有 GetAll()方法
public IQueryable<User> GetAllUsers()
{
_repository = new UserRepository();
return _repository.GetAll().AsQueryable();
}
以及用户存储库中的 GetAll()函数
public IQueryable<User> GetAll()
{
InstaStoryDB db = new InstaStoryDB();
var ret = db.Users.Include("InstagramUser").Include("FacebookUser").AsQueryable();
foreach(User user in ret)
{
user.InstagramID = user.InstagramUser.InstagramID; //<-- I'm adding here the value to the property
}
return ret;
}
这是 InstagramUser Model
[DataContract]
public class InstagramUser
{
[DataMember]
public long UserId { get; set; }
[DataMember]
public string InstagramID { get; set;
}
一切顺利。
我对User模型进行了更改并添加了包含InstagramUser
的{{1}},因此我添加了[NotMapped]属性以从 DB <中的User表中删除InstagramID / strong>因为InstagramUser已经包含了InstagramID。
我什么时候尝试像这样使用Odata: localhost:555 / api / users /?$ filter = InstagramID eq'456456546' 它失败并返回一个不存在InstagramID属性的错误。
如何在 NotMapped 属性上使用Odata过滤器?
答案 0 :(得分:8)
这适用于我在Web API中使用OData v4:
var t = modelBuilder.StructuralTypes.First(x => x.ClrType == typeof(User));
t.AddProperty(typeof(User).GetProperty("InstagramID"));
答案 1 :(得分:4)
您可以在此处找到解决方法:http://forums.asp.net/t/1887669.aspx?OData+EF+Model+with+custom+calculated+properties
例如
public IQueryable<DomainModel> GetAllDomains(ODataQueryOptions<Domains> queryOptions)
{
var query = queryOptions.ApplyTo(objectContext.Domains) as IQueryable<Domain>;
return query.AsEnumerable().Select(d => new DomainModel
{
Name = d.Name,
Activated = d.Activated,
Address = d.Address,
AdminUserName = d.AdminUserName,
DateCreated = d.DateCreated,
Enabled = d.Enabled,
Subscription = (SubscriptionTypes)d.SubscriptionType,
Website = d.Website,
StatsUpdatePending = d.StatsUpdatePending,
LastHousekeeping = d.LastHousekeeping,
CalculatedProperty = calculator.Calculate(d.Name, d.Activated)
}).AsQueryable();
}
答案 2 :(得分:2)
我找到了一个与Jason Steele类似的解决方案,但使用方法EntityType和Property如下:
modelBuilder.EntityType<User>().Property(u => u.InstagramID);
结果是一样的。如果查看Property方法的源代码,您会发现它正在获取PropertyInfo,然后将其添加到该类的StructuralTypeConfiguration中:
PropertyInfo propertyInfo = PropertySelectorVisitor.GetSelectedProperty(propertyExpression);
PrimitivePropertyConfiguration property = _configuration.AddProperty(propertyInfo);