0

I have an entity (A) which has a related entity (B). When I load A I want to load B automatically.

I have set the following in the OnModelCreating():

ModelBuilder.Entity<A>().HasRequired(o => o.CreatedByAdministrator).WithMany().HasForeignKey(o => o.CreatedBy);

Besides I have set:

public DbSet<A> As { get; set; } 
public DbSet<B> Bs { get; set; } 

When I load a list with entities A - I say:

context.As.Include("CreatedByAdministrator").ToList();

It seems to work perfect. But I want to make sure - that when I save/update/and delete A - it should never affect the related B. How do I do that?

Peter NB
  • 71
  • 3

2 Answers2

0

Delete

Set WillCascadeOnDelete on your mapping to false.

ModelBuilder.Entity<A>().HasRequired(o => o.CreatedByAdministrator).WithMany().HasForeignKey(o => o.CreatedBy).WillCascadeOnDelete(false);

Save and update

If you haven't edited a property in your related entity, it won't update/save anything. If you did edit something, you can always set that property to null.

Or you can set the state of that object to Unchanged.

context.Entry(entity).State = EntityState.Unchanged;
Loetn
  • 3,832
  • 25
  • 41
0

When you get(fetch data) from A then you can retrive data of related entity

Get/Fetch

e.g.
var  model  = a.tolist()

in view 
Model.b.yourproperty  

Update/Save

If You want to update and save then you have to write update or save functionality.otherwise manually it not affect to your related property.

Delete

plz check fundamental here

also agree with @Loetn for delete.

Community
  • 1
  • 1
MSTdev
  • 4,507
  • 2
  • 23
  • 40