I have a class called Userand it is [Serializable] and inherited from base class IdentityUser an Entity Framework class and Non Serializable.
I have a property in Booking class with type User and Booking class is Serializable I am trying to serialize the booking object using BinaryFormatter but I can't because of IdentityUser class and I get this error :
'Type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser' in
Assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as
serializable.'
Is there a way to ignore this property because I don't think there is away to make 'IdentityUser' as Serializable.
[Serializable]
public class User : IdentityUser
{
public String FirstName { get; set; }
}
[Serializable]
public class Booking
{
[ForeignKey("Guest")]
public string GuestId { set; get; }
public virtual User Guest { set; get; }
}
BinaryFormatter serializes the public and private fields of a object -- not the properties. For an auto-implemented property the secret backing field is what is actually serialized.
Normally, if you do not want a field to be serialized, you can apply the [NonSerialized] attribute, and BinaryFormatter will skip it. In c# 7.3 and later, it's possible to do this to the secret backing field of an auto-implemented property by using a field-targeted attribute:
[field: NonSerialized]
public virtual User Guest { set; get; }
See: Auto-Implemented Property Field-Targeted Attributes and What's new in C# 7.3.
Prior to c# 7.3 there is no way to apply an attribute to the backing field of an auto-implemented property. Thus you need to make the backing field be explicit:
[Serializable]
public class Booking
{
[ForeignKey("Guest")]
public string GuestId { set; get; }
[NonSerialized]
User guest;
public virtual User Guest { set { guest = value; } get { return guest; } }
}
Incidentally, if you need to serialize some of the information in User, you could consider implementing ISerializable, or replacing instances of User with serialization surrogates.
Related
I have common field in all tables
public Guid UserId { get; set; }
How can I fill in this field without repeating the code?
I want to do it using the interface.
It would be better to create base class and inherit from it in each model class.
public class BaseModel
{
public Guid UserId { get; set; }
}
public class Table : BaseModel
{
}
If you use an interface, you will still need to implement the property in every class.
In EF Core 3.1 I am attempting to implement a Concurrency Token for my base class. I run into problems for entities stored in shared tables of which a derived class owns an entity. When the derived class holds a single property, it is advised to create this property as a shadow property on the base class. However with the property that represents an owned type I don't know how I can do this. I am trying to avoid putting in a shadow property for every single property in the owned type.
The class from which all entities are derived:
public class EntityClass
{
///...
[Timestamp]
public byte[] ConcurrencyToken { get; set; }
}
An example of a base class and the derived class that holds an additional owned type:
public class Transaction : EntityClass
{
///...
public Company Counterparty { get; set; }
public Currency TransactionCurrency { get; set; }
}
public class CashTransaction : Transaction
{
///...
public Currency BankAccountCurrency { get; set; }
}
Currency is an owned model and its properties are stored in the table related to Transaction:
[Owned, ComplexType]
public class Currency
{
///...
public string CurrencyName { get; set; }
public string CurrencySymbol { get; set; }
}
When I add the migration the following error shows:
Entity type 'CashTransaction.BankAccountCurrency#Currency' doesn't contain a property mapped to the store-generated concurrency token column 'ConcurrencyToken' that is used by another entity type sharing the table 'Transaction'. Add a store-generated property mapped to the same column to 'CashTransaction.BankAccountCurrency#Currency'. It can be in shadow state.
I tried to configure the shadow property with a few tries, for example:
modelBuilder.Entity<Transaction>().OwnsOne<Currency>("BankAccountCurrency");
EDIT:
Below does not work: it leads to issues with change tracking on derived class.
For a while I thought below would work: create a private property of the owned entity, and then configure this in the modelBuilder call:
public class Transaction : EntityClass
{
///...
public Company Counterparty { get; set; }
public Currency TransactionCurrency { get; set; }
private Currency BankAccountCurrency { get; set; }
}
modelBuilder.Entity<Transaction>().OwnsOne(typeof(Currency), nameof(CashTransaction.BankAccountCurrency));
I am creating an application using Entity Framework 6.0 and Database-First approach. After I updated model from the database, I realised the essential need models to be derived from a BaseEntity class. The reason is that I need the base class to access the Id property using the BaseEntity class because the model class is often not specified.
My current solution is simple. According to Luke answer I implemented the partial class schema and directly derived a model class from RootEntity. In fact, the RootEntity class has the Id property as the model classes do. The compiler says CS0114 warning that classes should override properties. Since the model is autogenerated it cannot override properties.
What is the best practice to solve the particular issue? I'd like to implement a cleared architecture but this unpretty pattern may confuse anyone who reads my code.
// autogenerated EF code
public partial class Education
{
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime AwardDate { get; set; }
public Nullable<int> PersonId { get; set; }
public virtual Person Person { get; set; }
}
// the base custom class I wont others to be derived from
public class RootEntity
{
public int Id { get; set; }
}
// partial class deriving
public partial class Education : RootEntity { }
EDIT:
The best solution I've found is to release the RootEntity class as an interface IPrimary. It also doesn't allow to directly create an object and provides a clearer definition of the required functionality.
public interface IPrimary
{
int Id { get; set; }
}
The best solution I've found is to release the RootEntity class as an interface IPrimary. It also doesn't allow to directly create an object and provides a clearer definition of the required functionality.
public interface IPrimary
{
int Id { get; set; }
}
public partial class Education : IPrimary { }
Recently when I read the default behavior of DataContractSerializer, I get the rules from MSDN, however I do not understand the first rule which I extracted as below:
The DataContractSerializer infers a data contract from types without attributes using the default properties of the newly created types.
How do I interpret this statement, if some one has clear idea, could you help, I know that "without attributes", the attribute means DataContract attribute, however what does that "default properties" refer to. Is there something called "default properties" in a custom type?
If you a have type referenced within another class that has [DataContract] attribute, then DataContractSerializer will serialize the referenced type even if it is not attributed with [DataContract]. Serialization will happen on all public properties, unless the property is attributed with [IgnoreDataMember].
For example:
[DataContract]
public class ClassA
{
public ClassB MyData { get; set; }
public string SomeString { get; set; }
public int SomeNumber { get; set; }
}
public class ClassB
{
public string SomeOtherInfo { get; set; }
public int SomeOtherNumber { get; set; }
}
In the above code, ClassB will be serialized based on its default properties, which in this case are all the public properties: "SomeOtherInfo" and "SomeOtherNumber".
I have an existing class in an external assembly which I can't change.
I would like to serialize an object from this class with Newtonsoft JSON.Net, but not all the properties.
Normally I can do this with the JsonIgnoreAttribute attribute like this:
public class TestJsonClass
{
public string PropA { get; set; }
[JsonIgnoreAttribute]
public string PropB { get; set; }
}
But since I can't change the class, is there a way to ignore a property without attributes?
Try inherit class and override property with appropriate annotations or copy property values in a completely new class.