EF Code First: How to keep a virtual collection private while still creating my database model correctly?

I use Code First to automatically create my database, and it works fine by creating a table Ordersand a table OrderLines, as expected when I add some test data.

I have the following class Order:

public class Order
{
    public int OrderID { get; set; }

    public void AddItem(string productCode, int quantity)
    {
        var existingLine = OrderLines.FirstOrDefault(x => x.ProductOption.ProductCode == item.ProductCode);

        if (existingLine == null)
            OrderLines.Add(new OrderLine { ProductOption = item, Quantity = quantity });
        else
            existingLine.Quantity += quantity;
    }

    public void RemoveItem(string productCode)
    {
        OrderLines.Remove(OrderLines.Where(x => x.ProductOption.ProductCode == productCode).FirstOrDefault());
    }

    public virtual ICollection<OrderLine> OrderLines { get; set; }

    public Order()
    {
        OrderLines = new List<OrderLine>();
    }
}

I really want to encapsulate the collection OrderLines, which makes it impossible for class consumers to directly add and remove elements to / from it (using the Add/ RemoveICollection methods ), and instead force them to use my own methods AddItemand RemoveItem.

, , EF , EF OrderLines table/foreign.

, , , internal , , OrderLines.

, , - ? !

, , ; . , , , , -, - - ?

+3
3

, , , , , . , , , - -, , .

. , , , . - RemoveAllItems() Order, . , , . , .

, , . ( ) , , -.

, , . , ( ), -. , OrderItemService, , . - , , db.

, , -, , , , , . .

+1

, , ReadOnlyCollectionBase , MSDN?

0

, , API OnModelCreating, , , , :

public class YourContext : DbContext
{
   public DbSet<Order> Orders { get; set; }
   public DbSet<OrderLine> OrderLines { get; set; }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Order>() 
           .HasMany(o => o.OrderLines) 
           .WithRequired(l => l.OrderId) 
           .HasForeignKey(l => l.OrderId);

   }
}

This will make your OrderLines read-only:

public class YourContext : DbContext
{
   public DbSet<Order> Orders { get; set; }

   public DbSet<OrderLine> OrderLines 
   { 
      get { return set<OrderLine>(); }
   }
}

I hope this helps you, please take a look at this blog post: EF Feature CTP5: Free API Samples

0
source

Source: https://habr.com/ru/post/1791987/


All Articles