How to work with Portable Class Library and EF Code-first?

我的梦境 提交于 2019-12-04 03:08:52

Don't use attributes. Use fluent API instead and create separate assembly for persistence (EF) which will reference your model assembly. Persistence assembly will be use used by your WebAPI layer.

I use a modified approach than Mikkel Hempel's, without the need to use pre processing directives.

  1. Create a standard .NET class library, call it Models
  2. Create a partial class representing what you want to be shared

    public partial class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
  3. For non-portable code (like DataAnnotations), create another partial class and use Metadata

    [MetadataTypeAttribute(typeof(Person.Metadata))]
    public partial class Person
    {
        internal sealed class Metadata
        {
            private Metadata() { } // Metadata classes shouldn't be instantiated
    
            // Add metadata attributes to perform validation
            [Required]
            [StringLength(60)]
            public string Name;
        }
    }
    
  4. Create a Portable Class Library, and add the class from step 2 "As Link"

When I need my domain-project across multiple platforms, I usually:

  1. Create the standard .NET-class library project for the domain code
  2. For each platform I create a platform specific class library
  3. For each platform specific class library I add the files from the standard .NET-class library as links (Add existing files -> As link) and hence they're updated automatically when you edit either the linked file or the original file.
  4. When I add a new file to the .NET-class library, I add it as links to the platform specific class libraries.
  5. Platform specific attributes (i.e. Table and ForeignKey which is a part of the DataAnnotations-assembly) can be opted out using the pre-processor tags. Lets say I have a .NET-class library with a class and a Silverlight-project with the linked file, then I can include the .NET-specific attributes by doing:

    #if !SILVERLIGHT
    [Table("MyEntityFrameworkTable")]
    #endif 
    public class MyCrossPlatformClass 
    {
        // Blah blah blah
    }
    

and only include the DataAnnotations-assembly in the .NET-class library.

I know it's more work than using the Portable Class Library, but you can't opt out attributes in a PCL like in the example above, since you're only allowed to reference shared assemblies (which again DataAnnotations is not).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!