문제

I'm using Entity Framework 5 in Database First approach and I am using edmx file.

Most of my entities have 6 common fields. Fields like CreatedAt, CreatedBy etc. Now, I implemented some functions as extensions that can only be applied to IQueryable of those Entities that have the common fields. But when I implement the extension method, it can be accessed by any type of IQueryable as it's typed T and I can only define that the type T should always be of one type.

So, I thought I can give a base class to the entities which has common fields and define type T as that base type. But, it seems I can't do this.

Any idea on how to solve this or implement what I have explained above?

도움이 되었습니까?

해결책

Don't create a base class. Create an Interface, like below:

public interface IMyEntity
{
    DateTime CreatedAt { get; set; }
    string CreatedBy { get; set; }
    // Other properties shared by your entities...
}

Then, your Models will be like this:

[MetadataType(typeof(MyModelMetadata))]
public partial class MyModel : IMyEntity
{
   [Bind()]  
   public class MyModelMetadata
   {
      [Required]
      public object MyProperty { get; set; }

      [Required]
      public string CreatedBy { get; set; }  
   }
}

다른 팁

I'm a fan of:

public interface IShared
{
  DateTime CreatedOn { get; set; }
}

public interface ISharedValidation
{
  [Required]
  DateTime CreatedOn { get; set; }
}


public interface IMyEntity: IShared
{
  // Entity Specifics
  string Username { get; set; }
}

public interface IMyEntityValidation: ISharedValidation
{
  [Required]
  string Username { get; set; }
}

Then, your Models will be like this:

[MetadataType(typeof(IMyEntityValidation))]
public partial class MyModel : IMyEntity
{
  public object CreatedOn { get; set; }
  public string Username { get; set; }  
}

If T4 generated by Entity Framework then your non-autogenerated class would look like:

[MetadataType(typeof(IMyEntityValidation))]
public partial class MyModel : IMyEntity
{
}

Typically, it is not recommended to use Bind in Asp.Net MVC.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top