我有一个客户端/服务器解决方案 using C#
, WPF
, ASP.NET WebAPI
and Entity Framework
。客户端和服务器类分享模型在他的项目中。现在我正在尝试使用 Xamarin Forms 创建一个新客户端并将模型共享给,但是实体框架属性(MaxLength
, Index
, NotMapped
等),是在 PCL 中不兼容。所以这是我尝试过的事情:
将 Microsoft.EntityFrameworkCore 导入到 PCL 模型
如上所述here https://blog.xamarin.com/building-android-apps-with-entity-framework/,您应该能够将实体框架与 Xamarin 表单一起使用,因此我将 PCL 转换为 NetStandard 1.3,并且它有效,每个 EntityFramework 属性都是允许的。但现在服务器项目与该标准不兼容,我无法在模型项目中添加像 prism 和 Newtonsoft.Json 这样的包。
使用诱饵和开关技巧模拟 Xamarin 表单的属性
我已经尝试过所描述的方法here https://stackoverflow.com/a/16046668/5147720,基于在模型 PCL 中创建自定义属性,并在类库中重新定义它们。 MyClient.Droid 和 MyClient.UWP 重新定义属性,将其留空,而 MyServer 将使用实体框架功能重新定义它们。
自定义 IndexAttribute - 模型 PCL:
namespace Model.Compatibility
{
public class IndexAttribute : Attribute
{
public IndexAttribute()
{
}
}
}
自定义 IndexAttribute - 服务器端:
[assembly: TypeForwardedToAttribute(typeof(Model.Compatibility.IndexAttribute))]
namespace Model.Compatibility
{
public class MockedIndexAttribute : System.ComponentModel.DataAnnotations.Schema.IndexAttribute
{
public MockedIndexAttribute()
{
}
}
}
我测试这种方法调用var attribute = new Model.Compatibility.IndexAttribute();
。 MockedIndexAttribute 构造函数永远不会被调用。
创建共享项目而不是 PCL
这种方式虽然有点乱,但看起来还是可行的。只需为模型创建一个新的共享项目,并使用如下条件标志:
#if !__MOBILE__
[NotMapped, Index]
#endif
public Guid Id { get; set; }
我目前还没有完全部署这种方法,但如果我不能使前两种方法都不起作用,我会采用这种方法。
编辑 - 尝试使“诱饵和切换属性”方法发挥作用
正如@AdamPedley 所建议的并且this https://stackoverflow.com/a/27143002/5147720线程到,我在新的 PCL(Xamarin.Compatibility) 中重新定义了 IndexAttribute,使用与原始命名空间相同的命名空间:
namespace System.ComponentModel.DataAnnotations.Schema
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class IndexAttribute : Attribute
{
public IndexAttribute() { }
}
}
现在,我的 PCL 模型包含对 Xamarin.Compatibility 的引用,因此我可以在模型属性中使用 Index 属性:
[Index]
public Guid Id { get; set; }
然后,从我的服务器项目中,我调用下一行代码来检查调用了什么构造函数、自定义属性或 EntityFramework 定义的属性:
PropertyInfo prop = typeof(MyClass).GetProperty("Id");
object[] attributes = prop.GetCustomAttributes(true);
调用的构造函数是自定义的,因此它不起作用,因为它必须调用 EntityFramework 定义的属性。这就是我不知道的事情,使我的模型的 PCL 根据调用程序集选择自定义属性或 EF 属性的机制是什么。
我还在我的服务器项目中添加了一个文件,名为 TypeForwarding.Net.cs(如建议的here https://stackoverflow.com/a/21368529/5147720),其中包含:
[assembly: TypeForwardedTo(typeof(IndexAttribute))]
但仍然不起作用。