渴望加载实体框架

时间:2015-04-14 12:25:25

标签: c# entity-framework

所以,I was having a problem为了解决这个问题,我为TeamColour表创建了一个Entity。这使我可以像这样创建我的创建/更新方法:

[HttpPost]
[Route("")]
/// <summary>
/// Create a team
/// </summary>
/// <param name="model">The team model</param>
/// <returns>Nothing</returns>
public async Task<IHttpActionResult> Create(TeamBindingViewModel model)
{

    // If our model is invalid, return the errors
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Create our new model
    var team = new Team()
    {
        Name = model.Name,
        Sport = model.Sport
    };

    // Create a new transaction incase anything fails, it will rollback the changes
    using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
    {
        // Otherwise, create a new team
        this.service.Create(team);

        // Save the database changes
        await this.unitOfWork.SaveChangesAsync();

        // For each colour, insert into our lookup table
        foreach (var colour in model.Colours)
            this.teamColourService.Create(new TeamColour { ColourId = colour.Id, TeamId = team.Id });

        try
        {

            // Save the database changes
            await this.unitOfWork.SaveChangesAsync();
        }
        catch(Exception ex)
        {

        }

        // If everything is done correctly, call the complete method
        transaction.Complete();
    }

    // Return Ok
    return Ok(model);
}

[HttpPut]
[Route("")]
/// <summary>
/// Update a team
/// </summary>
/// <param name="model">The team model</param>
/// <returns>Nothing</returns>
public async Task<IHttpActionResult> Update(TeamBindingViewModel model)
{

    // If our model is invalid, return the errors
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Get our current team
    var team = await this.service.GetAsync(model.Id, "Colours");

    // Make changes to our team
    team.Name = model.Name;
    team.Sport = model.Sport;

    // Update the team
    this.service.Update(team);

    // For each colour that has to be removed, remove from our team colours
    foreach (var colour in team.Colours.ToList())
        if (!model.Colours.Any(c => c.Id == colour.Id))
            this.teamColourService.Remove(new TeamColour { ColourId = colour.Id, TeamId = model.Id });

    // For each colour that has to be added, add to our team colours
    foreach (var colour in model.Colours)
        if (!team.Colours.Any(c => c.Id == colour.Id))
            this.teamColourService.Create(new TeamColour { ColourId = colour.Id, TeamId = model.Id });

    // Save the database changes
    await this.unitOfWork.SaveChangesAsync();

    // Return Ok
    return Ok(model);
}

这解决了我原来问题中的问题。 我现在遇到的问题是,自从我的查找表创建实体后,当我使用预先加载时,没有任何颜色被拉回来。例如,这是我的get方法:

[HttpGet]
[Route("")]
/// <summary>
/// Gets a team by the id
/// </summary>
/// <param name="id">The id of the team</param>
/// <returns>A team</returns>      
public async Task<IHttpActionResult> Get(int id)
{
    return Ok(await this.service.GetAsync(id, "Colours", "Players", "Kits"));
}

正如你所看到的,这是试图让团队,并拉回颜色,球员和套件。 如果我们查看Team类,我们将看到定义的子项:

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sport { get; set; }

    public IList<Colour> Colours { get; set; }
    public IList<Kit> Kits { get; set; }
    public IList<Player> Players { get; set; }
}

在我将Lookup表创建为实际实体之前,将回退Colors,但是他们将新记录插入到Colors和TeamColours表中而不仅仅是TeamColours表中。 就像我说的那样,创建TeamColours表作为一个固定的实体,但似乎打破了急切的加载。 我的数据库上下文如下所示:

public class DatabaseContext : DbContext
{

    // Define our tables
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }

    public DbSet<Design> Designs { get; set; }
    public DbSet<Colour> Colours { get; set; }
    public DbSet<Kit> Kits { get; set; }
    public DbSet<Team> Teams { get; set; }
    public DbSet<Player> Players { get; set; }

    public DbSet<TeamColour> TeamColours { get; set; }

    /// <summary>
    /// static constructor (only gets called once)
    /// </summary>
    static DatabaseContext()
    {

        // Create the database and insert our records
        //Database.SetInitializer<DatabaseContext>(new DatabaseInitializer());
    }

    /// <summary>
    /// Default constructor
    /// </summary>
    public DatabaseContext()
        : base("DefaultConnection")
    {

        // Disable Lazy Loading
        base.Configuration.LazyLoadingEnabled = false;

        // Write our SQL to the debug window
        this.Database.Log = s => Debug.WriteLine(s);
    }

    /// <summary>
    /// Overrides the inherited OnModelCreated method.
    /// </summary>
    /// <param name="modelBuilder">The DbModelBuilder</param>
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        // Remove Cascading Delete
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Map the UserRoles table
        modelBuilder.Entity<User>()
            .HasMany(m => m.Roles)
            .WithMany()
            .Map(m =>
            {
                m.MapLeftKey("UserId");
                m.MapRightKey("RoleId");
                m.ToTable("UserRoles");
            });

        // Map the KitColours table
        modelBuilder.Entity<Kit>()
            .HasMany(m => m.Colours)
            .WithMany()
            .Map(m =>
            {
                m.MapLeftKey("KitId");
                m.MapRightKey("ColourId");
                m.ToTable("KitColours");
            });

        //// Map the TeamColours table
        //modelBuilder.Entity<Team>()
        //    .HasMany(m => m.Colours)
        //    .WithMany()
        //    .Map(m =>
        //    {
        //        m.MapLeftKey("TeamId");
        //        m.MapRightKey("ColourId");
        //        m.ToTable("TeamColours");
        //    });

        // Create our relationships
        modelBuilder.Entity<Kit>().HasRequired(m => m.Team).WithMany(m => m.Kits).Map(m => { m.MapKey("TeamId"); });
        modelBuilder.Entity<Kit>().HasRequired(m => m.Design).WithMany().Map(m => { m.MapKey("DesignId"); });
        modelBuilder.Entity<Player>().HasRequired(m => m.Team).WithMany(m => m.Players).Map(m => { m.MapKey("TeamId"); });

        // Add our keys to the lookup tables
        modelBuilder.Entity<TeamColour>().HasKey(model => new { model.TeamId, model.ColourId });
    }
}

所以,我的问题是,我怎样才能让我的渴望加载再次工作?

1 个答案:

答案 0 :(得分:0)

所以是的,我通过将虚拟属性更改为:

来修复此问题
public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sport { get; set; }

    public IList<TeamColour> Colours { get; set; }
    public IList<Kit> Kits { get; set; }
    public IList<Player> Players { get; set; }
}

无论如何我只对 colourId 感兴趣,所以这很好。