将项添加到列表/集合(首先使用MVC EF 4.1代码)

时间:2011-09-30 14:48:20

标签: asp.net-mvc ef-code-first one-to-many

将项目/对象添加到列表/集合中时出现问题。

这是我到目前为止所做的......

public abstract class Member 
{
    [DisplayName("ID")]
    public string MemberId { get; set; }

    [DisplayName("Date Applied")]
    public System.DateTime? DateApplied { get; set; }

    [DisplayName("Date Membered")]
    public System.DateTime? DateMembered { get; set; }

    [DisplayName("Member Type")]
    public int MemberTypeFlag { get; set; }

    private ICollection<Address> _Addresses;
    public virtual ICollection<Address> Addresses
    {
        get { return _Addresses ?? (_Addresses = new HashSet<Address>()); }
        set { _Addresses = value; }
    }
}

public class Person : Member
{
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [DisplayName("Date Of Birth")]
    public System.DateTime DateOfBirth { get; set; }
}

这就是我绘制它的方式..

public class MapAddress  : EntityTypeConfiguration<Address>
{
    public MapAddress()
        : base()
    {
        HasKey(a => a.MemberId).HasOptional(a => a.Member).WithMany(i => i.Addresses);
        Property(p => p.Address1).HasColumnName("ADDRESS1");
        Property(p => p.Address2).HasColumnName("ADDRESS2");
        Property(p => p.City).HasColumnName("CITY");
        Property(p => p.ZipCode).HasColumnName("ZIPCODE");
        Property(p => p.AddressTypeFlag).HasColumnName("ADDRESS_TYPE_FFLG");
        ToTable("MBR_ADDRESS");
    }
}

保存时出现错误..

“一个或多个实体的验证失败。有关详细信息,请参阅'EntityValidationErrors'属性。”

这是我添加到集合中的方式..

    public void Apply(PersonInformation member)
    {
        Person person = new Person();

        person = member.person;
        person.MemberId = CustomID.GenerateID();
        person.MemberTypeFlag = (int)Enum.Parse(typeof(EnumMemberType), "Person");
        person.DateApplied = DateTime.Now;

        Address baddress = new Address();
        baddress = member.billingAddress;
        Address paddress = new Address();
        paddress = member.premiseAddress;

        person.Addresses.Add(baddress);
        person.Addresses.Add(paddress);

        context.People.Add(person);
        context.SaveChanges();
    }

或者还有其他优雅的方式来保存具有多个地址的成员。

1 个答案:

答案 0 :(得分:0)

为什么要创建一个新人和2个新地址,然后再重新分配变量1行?你的例子中有很多冗余代码。

您的代码基本归结为以下内容:

public void Apply(PersonInformation member)
{
    member.person.MemberId = CustomID.GenerateID();
    member.person.MemberTypeFlag = (int)Enum.Parse(typeof(EnumMemberType), "Person");
    member.person.DateApplied = DateTime.Now;

    member.person.person.Addresses.Add(member.billingAddress);
    person.Addresses.Add(member.premiseAddress);

    context.People.Add(member.person);
    context.SaveChanges();
}