问题
I have an Entity Framework Code First model with a column that is not mapped which I still want to persist between the server and the client. The model looks similar to this with many more properties:
public class OwnerInformation
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(16)]
public byte[] SSNEncrypted { get; set; }
[NotMapped]
[MaxLength(9)]
[MinLength(9)]
public string SSN { get; set; }
}
When the metadata is retrieved by Breeze SSN is not part of it, but when the data is sent over the wire the SSN is there. I would like to let breeze deal with the mapping through the metadata, but I would like to be able to still pass SSN between the client and the server and track it's state as I need to encrypt it before it is saved to the DB.
I tried adding it after the metadata is fetched like this:
var ownerType = manager.metadataStore.getEntityType('OwnerInformation');
var sSN = new breeze.DataProperty({
name: 'sSN',
dataType: breeze.DataType.String,
isNullable: false,
maxLength: 9
});
ownerType.addProperty(sSN);
but I get the error: The 'OwnerInformation:#Models' EntityType has already been added to a MetadataStore and therefore no additional properties may be added to it.
Maybe I'm overthinking this and there is an easier way. I'm opened to any suggestions.
回答1:
I took a different approach and decided to change the metadata at runtime on the server. Here's how I did it.
public class MyContextProvider : EFContextProvider<MyContext>
{
protected override string BuildJsonMetadata()
{
string metadata = base.BuildJsonMetadata();
JObject json = JObject.Parse(metadata);
var entityOwnerInfo = json["schema"]["entityType"].Children().Where(j => (string)j["name"] == "OwnerInformation").SingleOrDefault();
var propertyArray = entityOwnerInfo["property"] as Newtonsoft.Json.Linq.JArray;
JToken ssnPropertyType = JToken.Parse(@"{
""name"": ""SSN"",
""type"": ""Edm.String"",
""fixedLength"": ""true"",
""maxLength"": ""9"",
""minLength"": ""9"",
""nullable"": ""false""}");
propertyArray.Add(ssnPropertyType);
return json.ToString();
}
}
回答2:
Actually it's a really good question. Breeze doesn't currently support modifying an EntityType after it has been added to the MetadataStore. But with your scenario I see the use case and I like your workaround.
I will add a feature request that allows this to be done more easily. Not sure yet exactly what this will look like, but... Thanks for the scenario.
来源:https://stackoverflow.com/questions/18118091/how-to-add-a-property-to-an-entitytype-after-it-has-been-added-to-the-data-store