开发者

Combining multi coloumn failover logic into a single property in Entity Framework 4.1

开发者 https://www.devze.com 2023-03-19 00:40 出处:网络
i am working on a legacy enterprise database that uses multiple columns to retrieve a part number the sql we currently use checks for a part number and if the part number is null then checks for the c

i am working on a legacy enterprise database that uses multiple columns to retrieve a part number the sql we currently use checks for a part number and if the part number is null then checks for the child part number what would be the best way of combining this logic into a single ef model property (eg Product.PartNumber )

I would like this to be invisible as possible so that only Par开发者_如何学GotNumber is visible externally to the data api


If you are using code-first approach the only way is to do a projection in custom linq-to-entities query:

var products = context.Products
                      .Select(p => new SomeNonMappedType
                           {
                               Id = p.Id,
                               // All other fields
                               PartNumber = p.PartNumber ?? p.Child.PartNumber // I hope this will work
                           });

If you are using EDMX you can use DefiningQuery or QueryView but whole your new entity will be readonly. More about those in another answer.


in theory couldnt you do something like this

public class Part
{ 
    public string PartNumber
    {
        get
        {
            return this.PartId ?? this.ChildPartId;
        }  
    }

    internal string PartId { get; set; }
    internal string ChildPartId { get; set; }
}



public class PartsContext : DbContext
{ 
    public DbSet<Part> Parts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Part>().Ignore(e => e.PartNumber);   
        base.OnModelCreating(modelBuilder);
    }
}

or is this still considered bad

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号