简体   繁体   中英

How to use one table for two different contexts in two different domains?

I have different contexts in two different domains and each domain contains an entity "country". Both entities should use the same table "country". One entity contains xzy properties and the other contains xz properties. The contexts do not know each other. The issue is that I am getting the error: "There is already an object named 'Country' in the database." What is the best approach in this case, please? Thank you in advance.

Normally an entity would belong only to one context/domain. if you need this entity in another domain, simply use the context it's defined in. there is nothing wrong with using multiple contexts in a transaction. What you're trying to do is conceptually and technically not recommended even though it is possible.

You need to change the name of the generated table: How to Specify Entity Framework Core Table Mapping?

Either use:

[Table("CountriesCustomTableName")]
public class Country{ x, y, z }

or override OnModelCreating like so:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Country>(entity => {
        entity.ToTable("CountriesCustomTableName");
    });
}

Remember to fully qualify your class names or you'll get confused or have ambiguous compilation errors

Edit

If you're trying to map 2 different entity models to the same table it sounds like you're pattern or design could be improved upon.

I would suggest you either need to use a full domain model, but only half populate it when you're inputting your 'half domain model'

public class Country {
    public string X { get; set; }
    public string Y { get; set; }
    public string Z { get; set; }

}


var country1 = new Country() { X = "A", Y = "B", Z = "C" };
var country2 = new Country() { X = "A", Z = "C" };

context.Countries.Add(country1);
context.Countries.Add(country2);

Or (more likely) This is some form of code smell and you need to abstract out the optional values into another table eg:

public class Country {
    public string X { get; set; }
    public string Z { get; set; }

}
public class CountryYInfo {
    public string Y { get; set; }

    public Country Country { get; set; }
    public int CountryId { get; set; }
}


var country1 = new Country() { X = "A", Z = "C" };
var countryInfo = new CountryYInfo { Y = "B", Country = country1 };

var country2 = new Country() { X = "A", Z = "C" };

context.Countries.Add(country1);
context.Countries.Add(country2);

If you want to share the country data between two domains, then "Country" is logically considered another domain. Reference the country record by its id instead of interdomain refrencing which is an awful practice in DDD.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM