shamim
shamim

Reputation: 6768

How to add/update/delete child entity

Work on Asp.net mvc entity framework,face problem on child entities add/update/delete portion.

enter image description here Here is my relationships

public class Client
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ClientId { get; set; }
    public string ClientName { get; set; }
    public string CompanyAddress1 { get; set; }
    public string CompanyAddress2 { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string ContactPerson { get; set; }
    public string ContactPersonPhone { get; set; }
    public virtual ICollection<Job> Jobs { get; set; }
}

public class Job
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int JobId { get; set; }
    public string JobDescription { get; set; }
    public decimal EstamationCost { get; set; }

    public DateTime EstemateDelevaryTime { get; set; }
    public virtual Client Client { get; set; }

}

public class Context : DbContext
{
    public DbSet<Job > Jobs { get; set; }
    public DbSet<Client> Clients { get; set; }
}

Please take a look at my job entity,it's not contain any parent id just contain the relation ship.

Want to know how to create any entry/update/delete on child entity.I used bellow syntax for create:

    [HttpPost]
    public async Task<ActionResult> Create(JobManageViewModel model)
    {
        if (ModelState.IsValid)
        {
            _unitOfWorkAsync.BeginTransaction();
            try
            {
                var application = model.ToDalEntity();
                application.ObjectState = ObjectState.Added;
                _jobService.Insert(application);
                var changes = await _unitOfWorkAsync.SaveChangesAsync();
                _unitOfWorkAsync.Commit();
                return RedirectToAction("Index");
            }
            catch
            {
                // Rollback transaction
                _unitOfWorkAsync.Rollback();
            }
        }
        LoadClientsInViewData();
        return View(model);
    }


public Job ToDalEntity(Job model)
{
    model.JobId = this.JobId;
    model.JobDescription = this.JobDescription;
    model.EstamationCost = this.EstamationCost;
    model.EstemateDelevaryTime = this.EstemateDelevaryTime;

    return model;
}

Problem is can not insert client information on Job table.How to insert/update/delete client information on job table

Upvotes: 0

Views: 175

Answers (1)

Pedro Benevides
Pedro Benevides

Reputation: 1980

This is a possible approach, but i strongly do not recommend you to do it, because it is really a bad practice, you are going to break SOLID principles, and so on.

But you could do this way:

Configure your relationship tables

I've created two separated classes, one for each table

Client Configuration

public class ClientEntityTypeConfiguration : EntityTypeConfiguration<Client>
{
    public ClientEntityTypeConfiguration()
    {
        HasKey(x => x.ClientId);
        Property(x => x.ClientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasMany(x => x.Jobs).WithOptional(x => x.Client);
    }
}

Job Configuration

public class JobEntityTypeConfiguration : EntityTypeConfiguration<Job>
{
    public JobEntityTypeConfiguration()
    {
        HasKey(x => x.JobId);
        Property(x => x.JobId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasOptional(x => x.Client).WithMany(x => x.Jobs);
    }
}

On your context class, you set those classes as your configuration:

public class MyContext : DbContext
{
    public DbSet<Client> Clients { get; set; }
    public DbSet<Job> Jobs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Configurations.Add(new ClientEntityTypeConfiguration());
        modelBuilder.Configurations.Add(new JobEntityTypeConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

The trick to add your already created client to your Job entity, is that you must set a new instance of Client, and set only the Id, and then tell to your Context that this instance is already exists on database.

var clientAlreadyExists = new Client {ClientId = 1};
context.Clients.Attach(clientAlreadyExists);
job.Client = clientAlreadyExists;        

context.Jobs.Add(product);

I recommend you to use Repository Pattern, and do not access your context directly from your Controller, and one more time a say this to you, your approach is a Bad Practice.

Upvotes: 1

Related Questions