我想将客户插入我的mongodb。我有一个Customer类和一个Address值对象。目前它不保存客户的地址,除非我将属性BsonElement放在Address的属性中。
我不想使用这个“BsonElement”属性我的“域名”还有其他选项吗?
我考虑过创建一个DTO,但我想要更容易一些。
这是我的代码:
客户类:
public class Customer : Entity<Customer>
{
public Customer(string firstName, string lastName, string phoneNumber, Address address, IUser user)
{
FirstName = firstName;
LastName = lastName;
Address = address;
User = user;
PhoneNumber = new PhoneNumber(phoneNumber);
}
public string FirstName { get; protected set; }
public string LastName { get; protected set; }
public Address Address { get; protected set; }
public PhoneNumber PhoneNumber { get; protected set; }
public IUser User { get; protected set; }
public bool ChangeName(string firstName, string lastName)
{
if (firstName == this.FirstName &&
lastName == this.LastName)
{
return false;
}
this.FirstName = firstName;
this.LastName = lastName;
Validations.Update("FirstName", this);
Validations.Update("LastName", this);
AddEvent(new CustomerNameChanged(Id, firstName, lastName));
return true;
}
public bool ChangeAddress(Address address)
{
if (Address == address)
{
return false;
}
this.Address = address;
Validations.Update("Address", this);
AddEvent(new CustomerAddressChanged(Id, Address));
return false;
}
public bool ChangePhoneNumber(string phoneNumber)
{
var newPhoneNumber = new PhoneNumber(phoneNumber);
if (newPhoneNumber == PhoneNumber)
{
return false;
}
this.PhoneNumber = PhoneNumber;
AddEvent(new CustomerPhoneChanged(Id, PhoneNumber.Number));
return true;
}
}
地址类:
public class Address : ValueObject<Address>
{
public Address(string addressLine1, string addressLine2, string city, string state, string zipCode)
{
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
City = city;
State = state;
ZipCode = zipCode;
}
public string AddressLine1 { get; }
public string AddressLine2 { get; }
public string City { get; }
public string State { get; }
public string ZipCode { get; }
public override bool Equals(ValueObject<Address> other)
{
var address = other as Address;
return address != null &&
AddressLine1 == address.AddressLine1 &&
AddressLine2 == address.AddressLine2 &&
City == address.City &&
State == address.State;
}
}
插入方法:
public void Insert(Customer customer)
{
_mongoDatabase
.GetCollection<Customer>("Customers")
.InsertOne(customer);
}
答案 0 :(得分:0)
我必须为我的客户和地址注册地图。
客户地图注册:
BsonClassMap.RegisterClassMap<Customer>(m =>
{
m.MapField(x => x.FirstName);
m.MapField(x => x.LastName);
m.MapField(x => x.LastName);
m.MapField(x => x.PhoneNumber);
m.MapField(x => x.Address);
m.MapField(x => x.User);
});
地址地图注册:
BsonClassMap.RegisterClassMap<Address>(m =>
{
m.MapField(x => x.AddressLine1);
m.MapField(x => x.AddressLine2);
m.MapField(x => x.City);
m.MapField(x => x.State);
m.MapField(x => x.ZipCode);
});
我在Startup.cs上调用所有地图,它有效。