ASP.NET MVC在创建对象时创建重复记录

时间:2016-10-04 05:38:54

标签: c# asp.net asp.net-mvc

我是ASP.NET的新手,我遇到了一个非常奇怪的重复记录问题。我将在这里深入研究代码:

我将公司模型定义为:

public class Company
{
    [Key]
    public int ID { get; set; }

    public DateTime DateCreated { get; set; }
    public virtual SubscriptionType SubscriptionType { get; set; }

    [Required]
    [Display(Name = "Company Name")]
    public String Name { get; set; }
}

public class CompanyDBContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
}

SubscriptionType模型定义为:

public class SubscriptionType
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }
}

public class SubscriptionTypeDBContext : DbContext
{
    public DbSet<SubscriptionType> SubscriptionTypes { get; set; }
}

SubscriptionType数据在Seed函数中设置如下:

var subscriptionTypes = new List<SubscriptionType>
        {
            new SubscriptionType { Name= "Free" },
            new SubscriptionType { Name= "Business" },
            new SubscriptionType { Name= "Enterprise" },
        };
        subscriptionTypes.ForEach(s => context.SubscriptionTypes.AddOrUpdate(p => p.Name, s));
        context.SaveChanges();

当我尝试在公共异步任务注册功能中创建用户时(我使用默认的ApplicationUser)我在用户注册时使用以下代码创建公司:

ApplicationDbContext db = new ApplicationDbContext();
            var subscription = db.SubscriptionTypes.Find(1);
            var company = new Company { Name = model.CompanyName, DateCreated = DateTime.UtcNow, SubscriptionType = subscription };
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Company = company };
            var result = await UserManager.CreateAsync(user, model.Password);

现在 - 公司应该有1个设置为SubscriptionType_ID,而是在SubscriptionType表中创建重复记录,并将SubscriptionType_ID设置为4。

ID | Name
-----------
1  | Free
2  | Business
3  | Enterprise
4  | Free

这是我的ApplicationDBContext:

public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<SubscriptionType> SubscriptionTypes { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Project> Projects { get; set; }
    public DbSet<Collection> Collections { get; set; }

为什么在这种情况下会创建重复记录?

1 个答案:

答案 0 :(得分:0)

您正在创建Company课程的新实例 - 从实体框架的角度来看 - 它是全新的Company,恰好具有相同的功能Name值(您可以在此处阅读更多内容:Entity Framework Change Tracking)。

您应该检查,如果用户提供的公司已经存在于您的数据库中,如果存在,则应该检索该公司并将其分配给Company类中的ApplicationUser属性。